I have a pandas data frame where i want to split every element in the first column and assign a column header to both the new columns. right now the column has no header.it is something like:
0 1 2 3 4
A|Item Name 25 26 31 40 45
B|Item Name 26 28 29 32 50
C|Item Name 31 32 12 32 11
Expected output
Ltr Itm 0 1 2 3 4
A Item Name 25 26 31 40 45
B Item Name 26 28 29 32 50
C Item Name 31 32 12 32 11
used the following code to try and convert the same:
df2 = pd.DataFrame(df2.row.str.split('|', 1).tolist(),
columns=['Let', 'Itm'])
but got error that there is no 'row' attribute in the dataframe.
any help is much appreciated. thanks.
If it is an index, you can use
df.index = df.index.str.split('|', expand = True)
df = df.reset_index().rename(columns = {'level_0': 'Ltr', 'level_1': 'Itm'})
You get
Ltr Itm 0 1 2 3 4
0 A Item Name 25 26 31 40 45
1 B Item Name 26 28 29 32 50
2 C Item Name 31 32 12 32 11
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments