【问题标题】:Using Pandas str.split with varying lengths of comma separated strings使用具有不同长度的逗号分隔字符串的 Pandas str.split
【发布时间】:2018-11-15 16:15:17
【问题描述】:

我正在尝试使用:

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

【问题讨论】:

    标签: python string pandas dataframe


    【解决方案1】:

    当然。只需将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
    

    【讨论】:

    • 感谢 jpp!像梦一样工作!
    猜你喜欢
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多