python - Pandas Dataframe 将数据拼接成 2 列,并用逗号和整数组成一个数字

标签 python pandas dataframe

我目前遇到两个问题:

我的数据框是这样的:

, 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.splitpop对于按分隔符的新列,然后是 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/

相关文章:

python - 使用以下命令从二进制数据字符串中提取日期和时间

python - 属性错误 : 'module' object (scipy) has no attribute *** Why does this error occur?

python - 如何遍历数据框,向系列添加新字段,然后将该系列附加到 csv?

python - Pandas 与 Numpy 索引 : Why this fundamental difference in ordering of indices?

python - 使用相同的键、多个值追加到字典

python - 从数据框中删除顶行

python - Django反向外键导致重复查询

python - attrs 如何欺骗调试器进入自动生成的代码?

python-3.x - 从一组选定的行中获取 NaN 值的索引

python - 如何根据条件删除 pandas 值并相应地移动行