我有以下代码
import pandas as pd
import numpy as np
import csv
location = r'C:\Users\tmaina\Desktop\scf\output.csv'
df = pd.read_csv(location,sep='\s*,\s*',engine='python')
for i, row in df.iterrows():
if row['COUPON_NUMBER'] == 1:
df.OND_ORIGIN = df.DEP_FROM
if df.loc[i+1,'PLDATE'] == row['PLDATE'] & row['TICKET_NUMBER'] ==df.loc[i+1,'TICKET_NUMBER'] &row['COUPON_NUMBER'] == 2:
df.OND_DEST = df.loc[i+1,'ARR_TO']
else:
df.OND_DEST = df.ARR_TO
elif row['COUPON_NUMBER'] == 2 & row['TICKET_NUMBER'] ==df.loc[i-1,'TICKET_NUMBER'] & row['PLDATE'] ==df.loc[i-1,'PLDATE']:
df.OND_ORIGIN==df.loc[i-1,'DEP_FROM']
df.OND_DEST = df.ARR_TO
elif row['COUPON_NUMBER'] == 3 & row['TICKET_NUMBER'] ==df.loc[i-1,'TICKET_NUMBER'] & row['PLDATE'] !=df.loc[i-1,'PLDATE']:
df.OND_ORIGIN = df.DEP_FROM
if df.loc[i+1,'PLDATE'] == row['PLDATE'] & row['TICKET_NUMBER'] ==df.loc[i-1,'TICKET_NUMBER']:
df.OND_DEST = df.loc[i+1,'ARR_TO']
else:
df.OND_DEST = df.ARR_TO
elif row['COUPON_NUMBER'] == 4 & row['TICKET_NUMBER'] ==df.loc[i-1,'TICKET_NUMBER']& row['PLDATE'] ==df.loc[i-1,'PLDATE']:
df.OND_ORIGIN = df.loc[i-1,'DEP_FROM']
df.OND_DEST = df.ARR_TO
df.to_csv('out.csv', sep=',',index = False)
以下列的输出是
COUPON_NUMBER TICKET_NUMBER DEP_FROM ARR_TO OND_ORIGIN OND_DEST PLDATE STOPOVER
1 1054737998 HRE NBO HRE NBO 20170419 O
2 1054737998 NBO KGL NBO KGL 20170419 X
3 1054737998 KGL NBO KGL NBO 20170519 O
4 1054737998 NBO HRE NBO HRE 20170419 X
所需的输出是
COUPON_NUMBER TICKET_NUMBER DEP_FROM ARR_TO OND_ORIGIN OND_DEST PLDATE STOPOVER
1 1054737998 HRE NBO HRE KGL 20170419 O
2 1054737998 NBO KGL HRE KGL 20170419 X
3 1054737998 KGL NBO KGL HRE 20170519 O
4 1054737998 NBO HRE KGL HRE 20170419 X
逻辑是,对于属于特定故障单的给定coupon_number
,我们会检查pldate
,如果同一天有多张优惠券,ond_origin
和{ {1}}应该是平等的。 ond_dest
是通过检查某个城市是否有停留来确定的。如果有,ond_dest
成为arr_to
,ond_dest
成为第一个没有停留的ond_origin
。
答案 0 :(得分:0)
您可以使用groupby
,Grouper
和transform
执行此操作,而不是遍历每一行。要获取每个组的第一个和最后一个,您可以使用this
如果PLDATE
是一个日期时间列,你可以做类似的事情
df['OND_ORIGIN'] = df.groupby(['TICKET_NUMBER', pd.Grouper(key='PLDATE', freq='1M')])['DEP_FROM'].transform(first)
df['OND_DEST'] = df.groupby(['TICKET_NUMBER', pd.Grouper(key='PLDATE', freq='1M')])['ARR_TO'].transform(last)
仅在您希望每月分组时才需要Grouper
。如果是按日期,则可以df.groupby(['TICKET_NUMBER', 'PLDATE', freq='1M'])