【问题标题】:Iterate over rows in Pandas and apply a function if two columns are equal遍历 Pandas 中的行并在两列相等时应用函数
【发布时间】:2018-04-09 16:26:42
【问题描述】:

我有一个如下所示的数据框:

import pandas as pd
inp = [{'ID':"a", 'start':100, 'end': 200}, {'ID':"b", 'start':250, 'end': 300},
 {'ID':"c", 'start':300, 'end': 300}, {'ID':"d", 'start':350, 'end': 500},
 {'ID':"e", 'start':600, 'end': 600}, {'ID':"f", 'start':700, 'end': 900}]
df = pd.DataFrame(inp)
df[['ID','start','end']]



ID  start   end
0   a   100 200
1   b   250 290
2   c   300 300
3   d   350 500
4   e   600 600
5   f   700 900

我想遍历我的 df 的行并应用一个函数,其中起点和终点列相等(即第 2 行和第 4 行),这样我就可以有一个变异的 df,如下所示:

ID  start   end
0   a   100 200
1   b   250 390
2   c   391 300
3   d   350 500
4   e   501 600
5   f   700 900

在变异的 df 中,起始值和结束值相等,我将起始值替换为上一列中的结束值+1。

我尝试像这样遍历行:

for index, row in df.iterrows():
  if(df['start'][i]==df['end'][i]):
      df[start'][i]=(df['end'][i-1]+1) # Here I am trying to refer to the end value in the previous row!
  else:
      df['start'][i]==df[start'][i] # Don't mess with the values if start and end are different!

对于如何解决此问题的任何提示/建议,我将不胜感激!

【问题讨论】:

    标签: python pandas dataframe lambda


    【解决方案1】:

    您不应该为可向量化计算迭代行。

    这是您可以通过pd.DataFrame.loc 实现逻辑的一种方式:

    df.loc[df['start'] == df['end'], 'start'] = df['end'].shift(1) + 1
    
    #   ID  end  start
    # 0  a  200  100.0
    # 1  b  300  250.0
    # 2  c  300  301.0
    # 3  d  500  350.0
    # 4  e  600  501.0
    # 5  f  900  700.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2019-05-28
      • 2016-01-10
      相关资源
      最近更新 更多