python - 使用 Pandas str.split 和不同长度的逗号分隔字符串

标签 python string pandas dataframe

我正在尝试使用:

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/

相关文章:

arrays - Ruby:字符串在数组中显示为字符串

python - 通过聚合按时间段对 DataFrame 进行分组

python - Pandas csv NaN 值替换为左侧列

python - pandas 系列/数据框的对数

python - 无法从网页中获取一定数量的正确值

python - 在 OpenCV Python 中获取 src 类型 CV_8UC3 到 CV_8UC1 时出错?

python - 使用Python : How can I convert given UT time to LST time Such that the function automatically increments day after 24 Hr check

java - 最短编辑距离?我需要它吗?

java - 字符串异常

python - 在 Python 中创建目录然后打开其中的文件时出错,但如果目录已存在则不会出错