I'm pulling data from a database and writing to a new Excel file for a report. My issue is that the last column of data has data that is separated by commas and needs to be separated into separate columns.
As an example I have data like the following:
Name Info
Mike "a, b, c, d"
Joe "a, f, z"
I need to break these letters out into separate columns. The a's, b's, etc. don't have to line up so that each letter is in the "correct" column. They just need to be broken out into separate columns.
I'm doing this in Python. I'm open to using other libraries like Pandas. There will be other columns included, not just two. I made a simple example.
Any help is appreciated.
IIUC:
df.assign(**df['Info'].str.split(',', expand=True).add_prefix('Info_'))
Output:
Name Info Info_0 Info_1 Info_2 Info_3
0 Mike a, b, c, d a b c d
1 Joe a, f, z a f z None
Note: You can also use join instead of assign (Using @coldspeed \s* to elimate spaces):
df.join(df['Info'].str.split('\s*,\s*', expand=True).add_prefix('Info_'))
From pandas str.split
df=pd.concat([df,df.Info.str.split(',',expand=True)],1)
df
Out[611]:
Name Info 0 1 2 3
0 Mike a, b, c, d a b c d
1 Joe a, f, z a f z None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With