【发布时间】:2019-02-12 20:06:49
【问题描述】:
我的数据框中有此列,其中包含字符串中的数字,例如"6,22,67,82"。我想将此字符串拆分为整数数组并将数组保留在数据框中。
h['htgt']=h['htgt'].split()
这不起作用,因为它试图拆分整个系列。
【问题讨论】:
标签: python arrays string pandas dataframe
我的数据框中有此列,其中包含字符串中的数字,例如"6,22,67,82"。我想将此字符串拆分为整数数组并将数组保留在数据框中。
h['htgt']=h['htgt'].split()
这不起作用,因为它试图拆分整个系列。
【问题讨论】:
标签: python arrays string pandas dataframe
您可以将pd.Series.str.split 与expand=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
【讨论】: