【问题标题】:Looping in Python: modify one column based on values in other columnsPython中的循环:根据其他列中的值修改一列
【发布时间】:2023-03-27 23:05:01
【问题描述】:

当前数据:

存储为 Pandas DataFrame

print(df)

col1 | col2 
A    | 1
B    | 3
C    | 3
D    | 7
E    | 4
C    | 3

目标:

如果 col1 是 A、C 或 E,我想创建一个将 col2 加 1 的新列。

col1 | col2  | col2_corrected
A    | 1     | 2
B    | 3     | 3
C    | 3     | 4
D    | 7     | 7
E    | 4     | 5
C    | 3     | 4

我失败的解决方案:

add_one_to_me = ['A','C','E']

if df.col1.isin(add_one_to_me):
    df.col2_corrected = df.col2 + 1
else: df.col2_corrected = df.col2

这会引发关于模棱两可的真相的错误,因为它正在评估整个系列的真相。

如何将其应用于 DataFrame 的每一行?我是 Python 和编程的新手,所以这是一个非常基本的问题。

提前致谢!

【问题讨论】:

    标签: python pandas loops if-statement


    【解决方案1】:
    # Copy the existing column over
    df['col2_corrected'] = df.col2
    
    # Increment the values of only those items where col1 is A C or E
    df.loc[df.col1.isin(['A', 'C', 'E']), 'col2_corrected'] += 1
    
    df
    Out[]: 
      col1  col2  col2_corrected
    0    A     1               2
    1    B     3               3
    2    C     3               4
    3    D     7               7
    4    E     4               5
    5    C     3               4
    

    你得到这个错误的原因是来自if df.col1.isin(add_one_to_me):这一行

    如果我们看一下:df.col1.isin(add_one_to_me)

    Out[]: 
    0     True
    1    False
    2     True
    3    False
    4     True
    5     True
    

    这与if 语句不符。您可以迭代地检查col1 中的每个项目,然后将col2_corrected 加一。这可以通过使用df.apply(...)for index, row in df.iterrows(): 来完成

    【讨论】:

    • 出于性能目的,如果你走这条路,我会避免使用iterrows 并坚持使用apply
    【解决方案2】:

    你可以利用True的整数值为1的事实

    df['col2_corrected'] = df['col2'] + df['col1'].isin(add_one_to_me)
    

    【讨论】:

      【解决方案3】:

      您也可以使用map 的功能,即

      df['new'] = df['col1'].map({'A':1,'C':1,'E':1}).fillna(0) + df['col2']
      
         col1  col2  new
      0    A     1  2.0
      1    B     3  3.0
      2    C     3  4.0
      3    D     7  7.0
      4    E     4  5.0
      5    C     3  4.0
      

      【讨论】:

        猜你喜欢
        • 2019-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多