首页 > 解决方案 > 在熊猫数据框中拆分字符串

问题描述

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

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

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

标签: pythonarraysstringpandasdataframe

解决方案


您可以使用pd.Series.str.splitwithexpand=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

推荐阅读