简体   繁体   中英

Using Pandas str.split with varying lengths of comma separated strings

I am trying to use:

ball_inf = ball_inf[['x','y','z', 'speed', 'Ball_Ownership', 'Ball_InPlay']] = ball_inf['base'].str.split('-',expand=True)

to spilt a dataframe with one column called 'base' which contains comma separated strings of varying lengths either 6 or 7, ie

"28,-7,0,82.00,A,Dead"
"38,-5,0,83.00,A,Dead,Go"

I get the warning:

Columns must be same length as key

Is there anyway of adding a NA if there is not a 7th item?

Sure. Just use str.split with , and join with your original dataframe:

df = pd.DataFrame({'strings': ['28,-7,0,82.00,A,Dead', '38,-5,0,83.00,A,Dead,Go']})

df = df.join(df.pop('strings').str.split(',', expand=True))

print(df)

    0   1  2      3  4     5     6
0  28  -7  0  82.00  A  Dead  None
1  38  -5  0  83.00  A  Dead    Go

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM