首页 > 解决方案 > 如何遍历 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')

标签: pythonpandasloops

解决方案


您可以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

推荐阅读