【问题标题】:Splitting string inside pandas dataframe在熊猫数据框中拆分字符串
【发布时间】:2019-02-12 20:06:49
【问题描述】:

我的数据框中有此列,其中包含字符串中的数字,例如"6,22,67,82"。我想将此字符串拆分为整数数组并将数组保留在数据框中。

  h['htgt']=h['htgt'].split()

这不起作用,因为它试图拆分整个系列。

【问题讨论】:

    标签: python arrays string pandas dataframe


    【解决方案1】:

    您可以将pd.Series.str.splitexpand=True 一起使用,然后转换为int。假设每个字符串中有相同数量的数字。

    h = pd.DataFrame({'htgt': ['6,22,67,82', '12,45,65,14', '54,15,9,94']})
    
    res = h['htgt'].str.split(',', expand=True).astype(int)
    
    print(res)
    
        0   1   2   3
    0   6  22  67  82
    1  12  45  65  14
    2  54  15   9  94
    

    【讨论】:

    • 感谢您的回答。字符串不包含相同数量的数字,所以我使用 expand is False,将数组保留为列中的条目。
    猜你喜欢
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2022-01-20
    • 2020-10-16
    • 2023-02-03
    相关资源
    最近更新 更多