[英]Splitting string inside pandas dataframe
I have this column in my dataframe which has numbers in a string like "6,22,67,82"
for example. 我的数据
"6,22,67,82"
有此列,该列中的数字例如为"6,22,67,82"
。 I want to split this strings into arrays of integers and keep the arrays in the dataframe. 我想将此字符串拆分为整数数组,并将这些数组保留在数据帧中。
h['htgt']=h['htgt'].split()
This does not work because it tries to split the whole series. 这不起作用,因为它试图拆分整个系列。
You can use pd.Series.str.split
with expand=True
and then convert to int
. 您可以将
pd.Series.str.split
与expand=True
,然后转换为int
。 Assumes you have an equal number of numbers in each string. 假设每个字符串中的数字数量相等。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.