【发布时间】:2021-04-02 10:24:20
【问题描述】:
最近,有人帮助我回答了一个问题https://stackoverflow.com/a/65417494/14872543,但我没有足够的知识来修改函数来解决相同的问题,即如果出现额外的字符串列,则在数据框中获取回程次数。
station from station to lgot count
0 20001 20040 stud 22
1 20001 20040 fed 33
0 20040 20001 stud 44
2 20040 20001 reg 55
3 20002 20015 stud 66
3 20015 20002 stud 77
station from station to lgot count count_back
0 20001 20040 stud 22 44
1 20001 20040 fed 33 0
2 20040 20001 reg 55 0
3 20002 20015 stud 66 77
我的解决方案,将 lgot 替换为 int lgot id(lgot ~7 的类型不多),将“station from”“station to”列连接使用解决方案中提出的功能。执行结果数据帧的反向转换。可能是对函数工作原理的误解
df.head()
station from station to lgot count
0 2030080 2030000 full 464
1 2030000 2030080 full 395
2 2030150 2030000 full 330
3 2030000 2030150 full 285
4 2030240 2030000 full 249
df.loc[df['lgot'] == 'full', 'lgot'] = '11'
df.loc[df['lgot'] == 'rzd', 'lgot'] = '22'
df.loc[df['lgot'] == 'fed', 'lgot'] = '33'
df.loc[df['lgot'] == 'reg', 'lgot'] = '44'
df.loc[df['lgot'] == 'stud', 'lgot'] = '55'
df.loc[df['lgot'] == 'voen', 'lgot'] = '66'
df['station to'] = df['station to'].astype('string')+df['lgot']
df['station from'] = df['station from'].astype('string')+df['lgot']
df['station to'] = df['station to'].astype('int')
df['station from'] = df['station from'].astype('int')
df.drop(['lgot'], axis='columns', inplace=True)
def roundtrip(df):
a, b, c, d = 'station from', 'station to', 'count', 'count_back'
idx = df[a] > df[b]
df = df.assign(**{d: 0})
df.loc[idx, [a, b, c, d]] = df.loc[idx, [b, a, d, c]].values
return df.groupby([a, b]).sum()
df = roundtrip(df)
df= df.reset_index()
df['lgot'] = df["station from"].astype('string').str.slice(start=-2)
df['station from'] = df['station from'].astype('string').str.slice(stop=7)
df['station to'] = df['station to'].astype('string').str.slice(stop=7)
df.head()
station from station to count count_back lgot
0 1003704 2030133 0 1 11
1 1003704 2030160 0 1 11
2 1003704 2031321 0 1 11
3 1003704 2030132 0 1 22
4 1003704 2030133 0 1 22
【问题讨论】:
-
在简单地寻求解决方案之前,您至少应该展示您所做的工作。
-
好的,我添加了,但看起来很恶心,就像我在用 excel 工作一样 :)