【问题标题】:pandas : update value if condition met in looppandas:如果在循环中满足条件,则更新值
【发布时间】:2019-04-06 05:41:24
【问题描述】:

如果满足条件,我必须更新数据框列。但是有多个条件和多个值要更新。因此我想循环执行。

数据框是这样的:

mode  car1  car2  bus1  bus2
car1   10    20    5     2
car2   11    22    3     1
bus1   4     4     2     2  
bus2   3     4     3     5

我意识到数据结构有点奇怪,但让我们继续吧。如果模式显示 car1,我希望新列值具有 car1 列中的值。以此类推。

我的代码是这样的:

targets = ['car1', 'car2', 'bus1', 'bus2']
for target in targets:
    df.loc[(df.mode==f'target'),'value']=df.[target]

这可行,但它会将不满足条件的行替换为 NaN。因此,我最终只得到新的 value 列,其中包含 bus2 行中 bus2 的值,但所有其他行中包含 NaN。

在 Stata 中,我会这样写:

gen value = .
foreach x in car1 car2 bus1 bus2 {
replace value = `x' if mode=="`x'"
}

在 Python 中寻找类似的代码!

【问题讨论】:

    标签: pandas for-loop conditional-statements


    【解决方案1】:

    这应该可行:

    df['newcol'] = 0
    for key, item in df.iterrows():
        df['newcol'].iloc[key] = item[item['mode']]
    

    【讨论】:

      【解决方案2】:

      pandas 中有lookup

      df['newvalue']=df.set_index('mode').lookup(df['mode'],df['mode'])
      df
      Out[184]: 
         mode  car1  car2  bus1  bus2  newcol  newvalue
      0  car1    10    20     5     2      10        10
      1  car2    11    22     3     1      22        22
      2  bus1     4     4     2     2       2         2
      3  bus2     3     4     3     5       5         5
      

      【讨论】:

        猜你喜欢
        • 2014-02-11
        • 1970-01-01
        • 1970-01-01
        • 2021-09-30
        • 1970-01-01
        • 1970-01-01
        • 2019-06-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多