Skip to content Skip to sidebar Skip to footer

Split A Pandas Dataframe Into Multiple Columns

Target I have a pandas dataframe as shown below and would like to split it where there is a blank-space, separating the 'command' and the float value. Dataframe - df e.g:

Solution 1:

My guess is you are attempting to call the "ROW" attribute for the DF, which does not exist. If you are attempting to do operations to select rows, I would suggest the .itterows() call to loop over just the rows you want at select indexes! Here is the best solution for what I think you are trying to achieve :)

import pandas as pd

Recreated Dummy Data

content = ['cl_bob_lower_amt"0"',
'cl_bobamt_lat"0"',
'cl_bobamt_vert"0"',
'cl_bobcycle"2"',
'cl_viewmodel_shift_left_amt"0"',
'cl_viewmodel_shift_right_amt"0"',]

Original Dataframe created

df = pd.DataFrame(content, columns = ['Value'])

Create a new dataframe (or re-assign to existing DF) by using .split call on Value.str

split_df = pd.DataFrame(df.Value.str.split(" ").tolist(), columns=["Command", "Value"])

Results:

                        Command   Value
0              cl_bob_lower_amt   "0"
1                 cl_bobamt_lat   "0"
2                cl_bobamt_vert   "0"
3                   cl_bobcycle   "2"
4   cl_viewmodel_shift_left_amt   "0"
5  cl_viewmodel_shift_right_amt   "0"

Solution 2:

df['command'], df['value'] = df["0"].str.split().str

df

                                    0                       command value
432              cl_bob_lower_amt "0"              cl_bob_lower_amt   "0"
433                 cl_bobamt_lat "0"                 cl_bobamt_lat   "0"
434                cl_bobamt_vert "0"                cl_bobamt_vert   "0"
435                   cl_bobcycle "2"                   cl_bobcycle   "2"
436   cl_viewmodel_shift_left_amt "0"   cl_viewmodel_shift_left_amt   "0"
437  cl_viewmodel_shift_right_amt "0"  cl_viewmodel_shift_right_amt   "0"

If the column is an integer 0

df['command'], df['value'] = df[0].str.split().str

Post a Comment for "Split A Pandas Dataframe Into Multiple Columns"