我目前遇到两个问题:
我的数据框是这样的:
, male_female, no_of_students
0, 24 : 76, "81,120"
1, 33 : 67, "12,270"
2, 50 : 50, "10,120"
3, 42 : 58, "5,120"
4, 12 : 88, "2,200"
我想实现的是:
, male, female, no_of_students
0, 24, 76, 81120
1, 33, 67, 12270
2, 50, 50, 10120
3, 42, 58, 5120
4, 12, 88, 2200
基本上我想将 male_female 转换成两列,将 no_of_students 转换成一列整数。我尝试了很多东西,将 no_of_students 列转换为另一种带有 .astype 的类型。但似乎没有什么能正常工作,我也找不到正确拆分 male_female 列的聪明方法。
希望有人能帮帮我!
最佳答案
使用str.split
与 pop
对于按分隔符的新列,然后是 strip
尾随值,replace
并在必要时转换为 integer
:
df[['male','female']] = df.pop('male_female').str.split(' : ', expand=True)
df['no_of_students'] = df['no_of_students'].str.strip('" ').str.replace(',','').astype(int)
df = df[['male','female', 'no_of_students']]
print (df)
male female no_of_students
0 24 76 81120
1 33 67 12270
2 50 50 10120
3 42 58 5120
4 12 88 2200
关于python - Pandas Dataframe 将数据拼接成 2 列,并用逗号和整数组成一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50681183/