我正在尝试使用:
ball_inf = ball_inf[['x','y','z', 'speed', 'Ball_Ownership', 'Ball_InPlay']] = ball_inf['base'].str.split('-',expand=True)
溢出一个名为“base”的数据帧,其中包含不同长度的逗号分隔字符串,长度为 6 或 7,即
"28,-7,0,82.00,A,Dead"
"38,-5,0,83.00,A,Dead,Go"
我收到警告:
Columns must be same length as key
如果没有第 7 项,是否有添加 NA
?
最佳答案
当然。只需将 str.split
与 、
一起使用,并将 join
与原始数据帧一起使用:
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
关于python - 使用 Pandas str.split 和不同长度的逗号分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53323622/