在熊猫数据框内拆分字符串

时间:2018-09-07 12:56:04

标签: python arrays string pandas dataframe

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

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

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

1 个答案:

答案 0 :(得分: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