python - 如何遍历 pandas 中的多个列并更改值?
问题描述
我有一个类似于下面的数据框的数据框:
column 1 column 2
4. Excellent 2. Poor
3. Good 2. Poor
2. Poor 1. No
1. No 4. Excellent
我正在使用 pandas 来分析这个数据框。我想自动更改数据框中每一行的值,但我知道如何逐列执行此操作。是否可以一次性遍历所有列并根据某些条件更改所有列的值?就我而言,我想将字符串“1. no”更改为整数 0;“2.差”乘整数2;整数 3 的“3.好”;和整数4的“4。优秀”。有谁知道我该怎么做?我想要的输出是:
column 1 column 2
4 2
3 2
2 1
1 4
我尝试使用 iteritems() 来做到这一点,但这是不可能的。前任:
for c, d in LTs_support.iteritems():
if d == '4. Excellent':
d.replace('4. Excellent', '4')
解决方案
您可以str.extract
在所有列和^(\d+)
正则表达式上使用来捕获初始数字:
df = df.apply(lambda c: c.str.extract('^(\d+)', expand=False)).astype(int)
输出:
column 1 column 2
0 4 2
1 3 2
2 2 1
3 1 4
推荐阅读
- javascript - JS 正则表达式将所有字符包裹在 Span 中
- javascript - 反应useEffect无法读取未定义的属性'map'
- c++ - glMapBuffer() 会造成巨大的性能损失?
- ios - 在iOS中触摸时如何模糊自定义按钮的标题,如系统UIButton的标题?
- c++ - 程序在 C++ 中不停地运行
- git - 如何提及在 git 中使用哪个 ssh 密钥?
- java - Java double 避免科学记数法但保留数据类型
- r - 需要在 R 中索引一个列表
- php - Laravel 数据透视表在 company_user 表中验证具有个人编号和公司的新用户的唯一性
- c# - 根据用户输入从多项选择题中提取答案