按 python 中的日期获取唯一列值

get unique column value by date in python

我已经生成了这个数据框:

np.random.seed(123)

len_df = 10
groups_list = ['A','B']
dates_list = pd.date_range(start='1/1/2020', periods=10, freq='D').to_list()

df2 = pd.DataFrame()
df2['date'] = np.random.choice(dates_list, size=len_df)
df2['value'] = np.random.randint(232, 1532, size=len_df)
df2['group'] = np.random.choice(groups_list, size=len_df)
df2 = df2.sort_values(by=['date'])
df2.reset_index(drop=True, inplace=True)

        date group  value
0 2020-01-01     A    652
1 2020-01-02     B   1174
2 2020-01-02     B   1509
3 2020-01-02     A    840
4 2020-01-03     A    870
5 2020-01-03     A    279
6 2020-01-04     B    456
7 2020-01-07     B    305
8 2020-01-07     A   1078
9 2020-01-10     A    343

我需要删除同一日期的重复组。我只希望一组在一个日期只出现一次。

结果

        date group  value
0 2020-01-01     A    652
1 2020-01-02     B   1174
2 2020-01-02     A    840
3 2020-01-03     A    870
4 2020-01-04     B    456
5 2020-01-07     B    305
6 2020-01-07     A   1078
7 2020-01-10     A    343

.drop_duplicates() 在 pandas 库中,您可以做到这一点。在 documentation.

中阅读更多内容
df2.drop_duplicates(subset=["date", "group"], keep="first")

Out[9]: 
        date group  value
0 2020-01-01     A    652
1 2020-01-02     B   1174
3 2020-01-02     A    840
4 2020-01-03     A    870
6 2020-01-04     B    456
7 2020-01-07     B    305
8 2020-01-07     A   1078
9 2020-01-10     A    343

您可以使用 drop_duplicates() 根据列的子集删除。但是,您需要指定要保留的行,例如first/last 行。

df2 = df2.drop_duplicates(subset=['date', 'group'], keep='first')

您正在数据帧上寻找 drop_duplicates 方法。

df2 = df2.drop_duplicates(subset=['date', 'group'], keep='first').reset_index(drop=True)
 
       
         date  value group
0 2020-01-01    652     A
1 2020-01-02   1174     B
2 2020-01-02    840     A
3 2020-01-03    870     A
4 2020-01-04    456     B
5 2020-01-07    305     B
6 2020-01-07   1078     A
7 2020-01-10    343     A