我想從 DataFrame 中洗掉所有行,這些行不包括每年和每月的 DataFrame 中的第一個日期。下面是一個例子:
pd.DataFrame([['2016-02-05', 22], ['2016-02-15', 15], ['2016-05-03', 18], ['2016-05-20', 9], ['2017-03-02', 10], ['2018-04-01', 11], ['2018-04-02', 12]],
columns=['date', 'qty'])
date qty
0 2016-02-05 22
1 2016-02-15 15
2 2016-05-03 18
3 2016-05-20 9
4 2017-03-02 10
5 2018-04-01 11
6 2018-04-02 12
我希望上面的 DataFrame 變成:
date qty
0 2016-02-05 22
2 2016-05-03 18
4 2017-03-02 10
5 2018-04-01 11
我將“日期”列轉換為日期時間并嘗試在回圈中執行此操作。但是,我沒有到達那里,而且我確信有一種比回圈執行更有效的方法。謝謝你的幫助!
uj5u.com熱心網友回復:
嘗試resample:
#convert to datetime if needed
df["date"] = pd.to_datetime(df["date"])
output = df.resample("M", on="date").first().dropna().reset_index(drop=True)
>>> output
date qty
0 2016-02-05 22.0
1 2016-05-03 18.0
2 2017-03-02 10.0
3 2018-04-01 11.0
如果要保留原始索引,可以執行以下操作:
output = df.assign(m=df["date"].dt.to_period("m")).drop_duplicates("m").drop("m",axis=1)
>>> output
date qty
0 2016-02-05 22
2 2016-05-03 18
4 2017-03-02 10
5 2018-04-01 11
uj5u.com熱心網友回復:
另一種方式,大概更快,因為它避免了擴展資料框
df.filter(df['date'].dt.to_period('M').drop_duplicates().index, axis = 0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360267.html
