Python => Pandas => DataFrame ==>执行drop_duplicates()时,有没有办法保留一些列从第一次出现和一些列从最后一次出现..?
让我们考虑以下示例。
<pre>
user swiped_in swiped_out ....
0 Bob 2019-02-25 09:50:32 2018-02-25 10:50:32 ....
1 Jane 2019-02-25 09:50:32 2019-02-25 11:50:32 ....
2 Alice 2019-02-25 09:50:32 2019-02-25 12:50:32 ....
3 Bob 2019-02-25 13:50:32 2019-02-25 14:50:32 ....
4 Bob 2019-02-25 15:50:32 2019-02-25 16:50:32 ....
</pre>
解决办法:使用DataFrameGroupBy.agg第一个和最后一个聚合函数,但所有其他列都丢失:
#if need convert to datetimes and sorting
c = ['swiped_in','swiped_out']
df[c] = df[c].apply(pd.to_datetime)
df = df.sort_values(c)
df = df.groupby('user', as_index=False).agg({'swiped_in':'first', 'swiped_out':'last'})
print (df)
user swiped_in swiped_out
0 Alice 2019-02-25 09:50:32 2019-02-25 12:50:32
1 Bob 2019-02-25 09:50:32 2019-02-25 16:50:32
2 Jane 2019-02-25 09:50:32 2019-02-25 11:50:32
如果有多个列具有唯一值,则需要聚合每列一些聚合函数 - 例如first:
print (df)
user swiped_in swiped_out col
0 Bob 2019-02-25 09:50:32 2018-02-25 10:50:32 q
1 Jane 2019-02-25 09:50:32 2019-02-25 11:50:32 w
2 Alice 2019-02-25 09:50:32 2019-02-25 12:50:32 e
3 Bob 2019-02-25 13:50:32 2019-02-25 14:50:32 r
4 Bob 2019-02-25 15:50:32 2019-02-25 16:50:32 y
c = ['swiped_in','swiped_out']
df[c] = df[c].apply(pd.to_datetime)
df = df.sort_values(c)
d = dict.fromkeys(df.columns.difference(['user', 'swiped_out']), 'first')
d['swiped_out'] = 'last'
df = df.groupby('user', as_index=False).agg(d)
print (df)
user col swiped_in swiped_out
0 Alice e 2019-02-25 09:50:32 2019-02-25 12:50:32
1 Bob q 2019-02-25 09:50:32 2019-02-25 16:50:32
2 Jane w 2019-02-25 09:50:32 2019-02-25 11:50:32
或者,如果多个新列的重复方式与user所有这些列的列聚合相同:
print (df)
user swiped_in swiped_out col
0 Bob 2019-02-25 09:50:32 2018-02-25 10:50:32 q
1 Jane 2019-02-25 09:50:32 2019-02-25 11:50:32 w
2 Alice 2019-02-25 09:50:32 2019-02-25 12:50:32 e
3 Bob 2019-02-25 13:50:32 2019-02-25 14:50:32 q
4 Bob 2019-02-25 15:50:32 2019-02-25 16:50:32 q
c = ['swiped_in','swiped_out']
df[c] = df[c].apply(pd.to_datetime)
df = df.sort_values(c)
cols = df.columns.difference(c).tolist()
df = df.groupby(cols, as_index=False).agg({'swiped_in':'first', 'swiped_out':'last'})
print (df)
col user swiped_in swiped_out
0 e Alice 2019-02-25 09:50:32 2019-02-25 12:50:32
1 q Bob 2019-02-25 09:50:32 2019-02-25 16:50:32
2 w Jane 2019-02-25 09:50:32 2019-02-25 11:50:32








暂无数据