【发布时间】:2020-08-11 09:22:07
【问题描述】:
我想对同一数据帧的两列进行减法运算,col1 行应该在位置 [i+1] 中,而 col2 应该在位置 [I] 中。 (col 1 是 col2 的继承者)。
我可以分享的部分代码,在最后返回时发布:
def calcul_TAT2(df):
i=0
for i in (range(len(df))):
if type(df['actual_gate_arrival_time']) is float or type(df['actual_gate_departure_time']) is float:
return 'NaN'
if df['actual_gate_arrival_time'].lower() =='nan' or df['actual_gate_departure_time'].lower()=='nan':
return 'NaN'
else :
actual_gate_arrival_time= (datetime(int(df['actual_gate_arrival_time'][6:10]),int(df['actual_gate_arrival_time'][3:5]),int(df['actual_gate_arrival_time'][:2]),int(df['actual_gate_arrival_time'][11:13]),int(df['actual_gate_arrival_time'][14:])))
actual_gate_departure_time= (datetime(int(df['actual_gate_departure_time'][6:10]),int(df['actual_gate_departure_time'][3:5]),int(df['actual_gate_departure_time'][:2]),int(df['actual_gate_departure_time'][11:13]),int(df['actual_gate_departure_time'][14:])))
return df.loc[i+1,'actual_gate_departure_time']-df.loc[i,'actual_gate_arrival_time']
DHA['TAT']=DHA.apply(calcul_TAT2, axis=1)
TypeError: ("cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [1] of <class 'int'>", 'occurred at index 593484569.0')
【问题讨论】:
-
你的数据框有索引标签吗? Loc 基于标签工作。例如,如果 i==5,它会查找等于 5 的索引标签。如果你想要正常的索引(如列表索引),你应该使用 iloc
-
是的,我已经尝试过了,它给了我另一个错误。我不知道是否还有另一种方法可以尝试使用 ix:'code' return df.iloc[i+1 ,10]-df.iloc[i,13] IndexingError: ('Too many indexers', '发生在索引 593484569.0')
-
您确定数据帧索引从 0 开始吗?有时“索引标签”有不同的值。例如,如果数据帧索引从 5 开始,则 df.loc[2] 不起作用但 df.iloc[2] 返回第三行
-
您可以尝试使用 df.iterrows 而不是 for 循环来避免这些情况。 stackoverflow.com/questions/16476924/…
-
感谢您的回复,不,@pooya 我不确定索引的开始如何验证
标签: python pandas dataframe jupyter-notebook calculated-columns