Pandas Split by delimiter when last delimiter may not exist
I am building out an ETL process in Python with the help of Pandas. I am trying to split some of the flat files by the delimiter "_
" in which, within the column I want to split, there are some rows that contain 3 delimiters and some that contain 4 delimiters (as an additional details part).
In the example a file that contains 3 delimiters within the column, if I add column 5 and use n=4, it gives me a Columns must be same length as key
error which makes sense as there are only 3 delimiters (if i use only 4 columns and n=3 it works but not what I want).
How can I get around this and when it spots the extra delimiter still splits it into a column and if not just leaves that column as null or blank. I also want to specify a n value as I do not want it to keep splitting at every delimiter. Any help would be amazing!
df[['column1','column2','column3','column4',
'column5 may or may not exisit']] = df['Column_to_split'].str.split('_',n=4,expand=True)
Example Data
0 Column_to_split nextcolumn nextcolumn nextcolumn nextcolumn
0 text_text_text text2 text3 text4 23
1 text_text_text text2 text3 text4 8
Desired Result
0 Column_to_split Column_to_split1 Column_to_split2 Column_to_split3 Column_to_split4 nextcolumn nextcolumn nextcolumn nextcolumn
0 text_text_text text text text null text2 text3 text4 23
1 text_text_text text text text null text2 text3 text4 8
python pandas
add a comment |
I am building out an ETL process in Python with the help of Pandas. I am trying to split some of the flat files by the delimiter "_
" in which, within the column I want to split, there are some rows that contain 3 delimiters and some that contain 4 delimiters (as an additional details part).
In the example a file that contains 3 delimiters within the column, if I add column 5 and use n=4, it gives me a Columns must be same length as key
error which makes sense as there are only 3 delimiters (if i use only 4 columns and n=3 it works but not what I want).
How can I get around this and when it spots the extra delimiter still splits it into a column and if not just leaves that column as null or blank. I also want to specify a n value as I do not want it to keep splitting at every delimiter. Any help would be amazing!
df[['column1','column2','column3','column4',
'column5 may or may not exisit']] = df['Column_to_split'].str.split('_',n=4,expand=True)
Example Data
0 Column_to_split nextcolumn nextcolumn nextcolumn nextcolumn
0 text_text_text text2 text3 text4 23
1 text_text_text text2 text3 text4 8
Desired Result
0 Column_to_split Column_to_split1 Column_to_split2 Column_to_split3 Column_to_split4 nextcolumn nextcolumn nextcolumn nextcolumn
0 text_text_text text text text null text2 text3 text4 23
1 text_text_text text text text null text2 text3 text4 8
python pandas
itertuples or iterrows? You said it varies each row in a single DataFrame?
– Scott Skiles
Nov 12 at 19:53
Sorry not sure how that would help? Yes it varies within each row of the dataframe so sometimes there may be 3 delimiters and sometimes there maybe 4, however, some files have only 3 and some have only 4.
– user2407147
Nov 12 at 19:57
Can you just change how you read in the data frame in the first place? Can you specify the column names atread_csv
? Also, can you provide a little sample data?
– Scott Skiles
Nov 12 at 20:02
Can't really provide specific column names as I want it to be slightly dynamic
– user2407147
Nov 12 at 22:25
add a comment |
I am building out an ETL process in Python with the help of Pandas. I am trying to split some of the flat files by the delimiter "_
" in which, within the column I want to split, there are some rows that contain 3 delimiters and some that contain 4 delimiters (as an additional details part).
In the example a file that contains 3 delimiters within the column, if I add column 5 and use n=4, it gives me a Columns must be same length as key
error which makes sense as there are only 3 delimiters (if i use only 4 columns and n=3 it works but not what I want).
How can I get around this and when it spots the extra delimiter still splits it into a column and if not just leaves that column as null or blank. I also want to specify a n value as I do not want it to keep splitting at every delimiter. Any help would be amazing!
df[['column1','column2','column3','column4',
'column5 may or may not exisit']] = df['Column_to_split'].str.split('_',n=4,expand=True)
Example Data
0 Column_to_split nextcolumn nextcolumn nextcolumn nextcolumn
0 text_text_text text2 text3 text4 23
1 text_text_text text2 text3 text4 8
Desired Result
0 Column_to_split Column_to_split1 Column_to_split2 Column_to_split3 Column_to_split4 nextcolumn nextcolumn nextcolumn nextcolumn
0 text_text_text text text text null text2 text3 text4 23
1 text_text_text text text text null text2 text3 text4 8
python pandas
I am building out an ETL process in Python with the help of Pandas. I am trying to split some of the flat files by the delimiter "_
" in which, within the column I want to split, there are some rows that contain 3 delimiters and some that contain 4 delimiters (as an additional details part).
In the example a file that contains 3 delimiters within the column, if I add column 5 and use n=4, it gives me a Columns must be same length as key
error which makes sense as there are only 3 delimiters (if i use only 4 columns and n=3 it works but not what I want).
How can I get around this and when it spots the extra delimiter still splits it into a column and if not just leaves that column as null or blank. I also want to specify a n value as I do not want it to keep splitting at every delimiter. Any help would be amazing!
df[['column1','column2','column3','column4',
'column5 may or may not exisit']] = df['Column_to_split'].str.split('_',n=4,expand=True)
Example Data
0 Column_to_split nextcolumn nextcolumn nextcolumn nextcolumn
0 text_text_text text2 text3 text4 23
1 text_text_text text2 text3 text4 8
Desired Result
0 Column_to_split Column_to_split1 Column_to_split2 Column_to_split3 Column_to_split4 nextcolumn nextcolumn nextcolumn nextcolumn
0 text_text_text text text text null text2 text3 text4 23
1 text_text_text text text text null text2 text3 text4 8
python pandas
python pandas
edited Nov 12 at 23:15
asked Nov 12 at 19:41
user2407147
55911331
55911331
itertuples or iterrows? You said it varies each row in a single DataFrame?
– Scott Skiles
Nov 12 at 19:53
Sorry not sure how that would help? Yes it varies within each row of the dataframe so sometimes there may be 3 delimiters and sometimes there maybe 4, however, some files have only 3 and some have only 4.
– user2407147
Nov 12 at 19:57
Can you just change how you read in the data frame in the first place? Can you specify the column names atread_csv
? Also, can you provide a little sample data?
– Scott Skiles
Nov 12 at 20:02
Can't really provide specific column names as I want it to be slightly dynamic
– user2407147
Nov 12 at 22:25
add a comment |
itertuples or iterrows? You said it varies each row in a single DataFrame?
– Scott Skiles
Nov 12 at 19:53
Sorry not sure how that would help? Yes it varies within each row of the dataframe so sometimes there may be 3 delimiters and sometimes there maybe 4, however, some files have only 3 and some have only 4.
– user2407147
Nov 12 at 19:57
Can you just change how you read in the data frame in the first place? Can you specify the column names atread_csv
? Also, can you provide a little sample data?
– Scott Skiles
Nov 12 at 20:02
Can't really provide specific column names as I want it to be slightly dynamic
– user2407147
Nov 12 at 22:25
itertuples or iterrows? You said it varies each row in a single DataFrame?
– Scott Skiles
Nov 12 at 19:53
itertuples or iterrows? You said it varies each row in a single DataFrame?
– Scott Skiles
Nov 12 at 19:53
Sorry not sure how that would help? Yes it varies within each row of the dataframe so sometimes there may be 3 delimiters and sometimes there maybe 4, however, some files have only 3 and some have only 4.
– user2407147
Nov 12 at 19:57
Sorry not sure how that would help? Yes it varies within each row of the dataframe so sometimes there may be 3 delimiters and sometimes there maybe 4, however, some files have only 3 and some have only 4.
– user2407147
Nov 12 at 19:57
Can you just change how you read in the data frame in the first place? Can you specify the column names at
read_csv
? Also, can you provide a little sample data?– Scott Skiles
Nov 12 at 20:02
Can you just change how you read in the data frame in the first place? Can you specify the column names at
read_csv
? Also, can you provide a little sample data?– Scott Skiles
Nov 12 at 20:02
Can't really provide specific column names as I want it to be slightly dynamic
– user2407147
Nov 12 at 22:25
Can't really provide specific column names as I want it to be slightly dynamic
– user2407147
Nov 12 at 22:25
add a comment |
1 Answer
1
active
oldest
votes
Maybe I'm missing something; does this approach work for you?
import pandas as pd
df = pd.DataFrame(["text1, text2, text3, text4", "text1, text2, text3, text4, text5"], columns=["column_name"])
print(df)
Output:
column_name
0 text1, text2, text3, text4
1 text1, text2, text3, text4, text5
Split the single column into many columns:
df_split = df["column_name"].str.split(",", expand=True)
print(df_split)
Output:
0 1 2 3 4
0 text1 text2 text3 text4 None
1 text1 text2 text3 text4 text5
You can rename the columns after this operation.
df_split.rename(columns=0:"column1", inplace=True)
print(df_split)
Output:
column1 1 2 3 4
0 text1 text2 text3 text4 None
1 text1 text2 text3 text4 text5
Alt approach, after your comment:
df = pd.DataFrame([["text1, text2, text3, text4",
"text1, text2, text3, text4, text5"],
["text1, text2, text3, text4",
"text1, text2, text3, text4, text5"]],
columns=["column1", "column2"])
print(df)
list_of_dfs =
for col in df.columns:
temp_df = df[col].str.split(",", expand=True)
print(temp_df)
list_of_dfs.append(temp_df)
split_df = pd.concat(list_of_dfs)
print(split_df)
Sample output:
0 1 2 3
0 text1 text2 text3 text4
1 text1 text2 text3 text4
0 1 2 3 4
0 text1 text2 text3 text4 text5
1 text1 text2 text3 text4 text5
0 1 2 3 4
0 text1 text2 text3 text4 NaN
1 text1 text2 text3 text4 NaN
0 text1 text2 text3 text4 text5
1 text1 text2 text3 text4 text5
Hey thanks for offering this however I have more than one column in my whole dataset. This just filters down to that one column and then break that out
– user2407147
Nov 12 at 22:24
@user2407147 updated w/a soln for multiple columns.
– Evan
Nov 12 at 22:32
I get this error "Can only use .str accessor with string values, which use np.object_ dtype in pandas"
– user2407147
Nov 13 at 12:58
Can you post the code (in your original question) that generates that error? TIA.
– Evan
Nov 13 at 15:08
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269026%2fpandas-split-by-delimiter-when-last-delimiter-may-not-exist%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Maybe I'm missing something; does this approach work for you?
import pandas as pd
df = pd.DataFrame(["text1, text2, text3, text4", "text1, text2, text3, text4, text5"], columns=["column_name"])
print(df)
Output:
column_name
0 text1, text2, text3, text4
1 text1, text2, text3, text4, text5
Split the single column into many columns:
df_split = df["column_name"].str.split(",", expand=True)
print(df_split)
Output:
0 1 2 3 4
0 text1 text2 text3 text4 None
1 text1 text2 text3 text4 text5
You can rename the columns after this operation.
df_split.rename(columns=0:"column1", inplace=True)
print(df_split)
Output:
column1 1 2 3 4
0 text1 text2 text3 text4 None
1 text1 text2 text3 text4 text5
Alt approach, after your comment:
df = pd.DataFrame([["text1, text2, text3, text4",
"text1, text2, text3, text4, text5"],
["text1, text2, text3, text4",
"text1, text2, text3, text4, text5"]],
columns=["column1", "column2"])
print(df)
list_of_dfs =
for col in df.columns:
temp_df = df[col].str.split(",", expand=True)
print(temp_df)
list_of_dfs.append(temp_df)
split_df = pd.concat(list_of_dfs)
print(split_df)
Sample output:
0 1 2 3
0 text1 text2 text3 text4
1 text1 text2 text3 text4
0 1 2 3 4
0 text1 text2 text3 text4 text5
1 text1 text2 text3 text4 text5
0 1 2 3 4
0 text1 text2 text3 text4 NaN
1 text1 text2 text3 text4 NaN
0 text1 text2 text3 text4 text5
1 text1 text2 text3 text4 text5
Hey thanks for offering this however I have more than one column in my whole dataset. This just filters down to that one column and then break that out
– user2407147
Nov 12 at 22:24
@user2407147 updated w/a soln for multiple columns.
– Evan
Nov 12 at 22:32
I get this error "Can only use .str accessor with string values, which use np.object_ dtype in pandas"
– user2407147
Nov 13 at 12:58
Can you post the code (in your original question) that generates that error? TIA.
– Evan
Nov 13 at 15:08
add a comment |
Maybe I'm missing something; does this approach work for you?
import pandas as pd
df = pd.DataFrame(["text1, text2, text3, text4", "text1, text2, text3, text4, text5"], columns=["column_name"])
print(df)
Output:
column_name
0 text1, text2, text3, text4
1 text1, text2, text3, text4, text5
Split the single column into many columns:
df_split = df["column_name"].str.split(",", expand=True)
print(df_split)
Output:
0 1 2 3 4
0 text1 text2 text3 text4 None
1 text1 text2 text3 text4 text5
You can rename the columns after this operation.
df_split.rename(columns=0:"column1", inplace=True)
print(df_split)
Output:
column1 1 2 3 4
0 text1 text2 text3 text4 None
1 text1 text2 text3 text4 text5
Alt approach, after your comment:
df = pd.DataFrame([["text1, text2, text3, text4",
"text1, text2, text3, text4, text5"],
["text1, text2, text3, text4",
"text1, text2, text3, text4, text5"]],
columns=["column1", "column2"])
print(df)
list_of_dfs =
for col in df.columns:
temp_df = df[col].str.split(",", expand=True)
print(temp_df)
list_of_dfs.append(temp_df)
split_df = pd.concat(list_of_dfs)
print(split_df)
Sample output:
0 1 2 3
0 text1 text2 text3 text4
1 text1 text2 text3 text4
0 1 2 3 4
0 text1 text2 text3 text4 text5
1 text1 text2 text3 text4 text5
0 1 2 3 4
0 text1 text2 text3 text4 NaN
1 text1 text2 text3 text4 NaN
0 text1 text2 text3 text4 text5
1 text1 text2 text3 text4 text5
Hey thanks for offering this however I have more than one column in my whole dataset. This just filters down to that one column and then break that out
– user2407147
Nov 12 at 22:24
@user2407147 updated w/a soln for multiple columns.
– Evan
Nov 12 at 22:32
I get this error "Can only use .str accessor with string values, which use np.object_ dtype in pandas"
– user2407147
Nov 13 at 12:58
Can you post the code (in your original question) that generates that error? TIA.
– Evan
Nov 13 at 15:08
add a comment |
Maybe I'm missing something; does this approach work for you?
import pandas as pd
df = pd.DataFrame(["text1, text2, text3, text4", "text1, text2, text3, text4, text5"], columns=["column_name"])
print(df)
Output:
column_name
0 text1, text2, text3, text4
1 text1, text2, text3, text4, text5
Split the single column into many columns:
df_split = df["column_name"].str.split(",", expand=True)
print(df_split)
Output:
0 1 2 3 4
0 text1 text2 text3 text4 None
1 text1 text2 text3 text4 text5
You can rename the columns after this operation.
df_split.rename(columns=0:"column1", inplace=True)
print(df_split)
Output:
column1 1 2 3 4
0 text1 text2 text3 text4 None
1 text1 text2 text3 text4 text5
Alt approach, after your comment:
df = pd.DataFrame([["text1, text2, text3, text4",
"text1, text2, text3, text4, text5"],
["text1, text2, text3, text4",
"text1, text2, text3, text4, text5"]],
columns=["column1", "column2"])
print(df)
list_of_dfs =
for col in df.columns:
temp_df = df[col].str.split(",", expand=True)
print(temp_df)
list_of_dfs.append(temp_df)
split_df = pd.concat(list_of_dfs)
print(split_df)
Sample output:
0 1 2 3
0 text1 text2 text3 text4
1 text1 text2 text3 text4
0 1 2 3 4
0 text1 text2 text3 text4 text5
1 text1 text2 text3 text4 text5
0 1 2 3 4
0 text1 text2 text3 text4 NaN
1 text1 text2 text3 text4 NaN
0 text1 text2 text3 text4 text5
1 text1 text2 text3 text4 text5
Maybe I'm missing something; does this approach work for you?
import pandas as pd
df = pd.DataFrame(["text1, text2, text3, text4", "text1, text2, text3, text4, text5"], columns=["column_name"])
print(df)
Output:
column_name
0 text1, text2, text3, text4
1 text1, text2, text3, text4, text5
Split the single column into many columns:
df_split = df["column_name"].str.split(",", expand=True)
print(df_split)
Output:
0 1 2 3 4
0 text1 text2 text3 text4 None
1 text1 text2 text3 text4 text5
You can rename the columns after this operation.
df_split.rename(columns=0:"column1", inplace=True)
print(df_split)
Output:
column1 1 2 3 4
0 text1 text2 text3 text4 None
1 text1 text2 text3 text4 text5
Alt approach, after your comment:
df = pd.DataFrame([["text1, text2, text3, text4",
"text1, text2, text3, text4, text5"],
["text1, text2, text3, text4",
"text1, text2, text3, text4, text5"]],
columns=["column1", "column2"])
print(df)
list_of_dfs =
for col in df.columns:
temp_df = df[col].str.split(",", expand=True)
print(temp_df)
list_of_dfs.append(temp_df)
split_df = pd.concat(list_of_dfs)
print(split_df)
Sample output:
0 1 2 3
0 text1 text2 text3 text4
1 text1 text2 text3 text4
0 1 2 3 4
0 text1 text2 text3 text4 text5
1 text1 text2 text3 text4 text5
0 1 2 3 4
0 text1 text2 text3 text4 NaN
1 text1 text2 text3 text4 NaN
0 text1 text2 text3 text4 text5
1 text1 text2 text3 text4 text5
edited Nov 12 at 22:37
answered Nov 12 at 21:40
Evan
1,116515
1,116515
Hey thanks for offering this however I have more than one column in my whole dataset. This just filters down to that one column and then break that out
– user2407147
Nov 12 at 22:24
@user2407147 updated w/a soln for multiple columns.
– Evan
Nov 12 at 22:32
I get this error "Can only use .str accessor with string values, which use np.object_ dtype in pandas"
– user2407147
Nov 13 at 12:58
Can you post the code (in your original question) that generates that error? TIA.
– Evan
Nov 13 at 15:08
add a comment |
Hey thanks for offering this however I have more than one column in my whole dataset. This just filters down to that one column and then break that out
– user2407147
Nov 12 at 22:24
@user2407147 updated w/a soln for multiple columns.
– Evan
Nov 12 at 22:32
I get this error "Can only use .str accessor with string values, which use np.object_ dtype in pandas"
– user2407147
Nov 13 at 12:58
Can you post the code (in your original question) that generates that error? TIA.
– Evan
Nov 13 at 15:08
Hey thanks for offering this however I have more than one column in my whole dataset. This just filters down to that one column and then break that out
– user2407147
Nov 12 at 22:24
Hey thanks for offering this however I have more than one column in my whole dataset. This just filters down to that one column and then break that out
– user2407147
Nov 12 at 22:24
@user2407147 updated w/a soln for multiple columns.
– Evan
Nov 12 at 22:32
@user2407147 updated w/a soln for multiple columns.
– Evan
Nov 12 at 22:32
I get this error "Can only use .str accessor with string values, which use np.object_ dtype in pandas"
– user2407147
Nov 13 at 12:58
I get this error "Can only use .str accessor with string values, which use np.object_ dtype in pandas"
– user2407147
Nov 13 at 12:58
Can you post the code (in your original question) that generates that error? TIA.
– Evan
Nov 13 at 15:08
Can you post the code (in your original question) that generates that error? TIA.
– Evan
Nov 13 at 15:08
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269026%2fpandas-split-by-delimiter-when-last-delimiter-may-not-exist%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
itertuples or iterrows? You said it varies each row in a single DataFrame?
– Scott Skiles
Nov 12 at 19:53
Sorry not sure how that would help? Yes it varies within each row of the dataframe so sometimes there may be 3 delimiters and sometimes there maybe 4, however, some files have only 3 and some have only 4.
– user2407147
Nov 12 at 19:57
Can you just change how you read in the data frame in the first place? Can you specify the column names at
read_csv
? Also, can you provide a little sample data?– Scott Skiles
Nov 12 at 20:02
Can't really provide specific column names as I want it to be slightly dynamic
– user2407147
Nov 12 at 22:25