我有兩個帶有日期時間索引的數據幀。使用日期時間索引的部分連接數據幀
import pandas as pd
d = {'dat': ['2016-01-01', '2016-01-02', '2016-01-03', '2017-01-01', '2017-01-02', '2017-01-03'],'x': [1, 2, 3, 4, 5, 6]}
df1 = pd.DataFrame(d)
df1.set_index(['dat'], inplace=True)
df1.index = pd.to_datetime(df1.index)
d = {'dat': ['2016-01-01', '2017-01-01'],'y': [10, 11]}
df2 = pd.DataFrame(d)
df2.set_index(['dat'], inplace=True)
df2.index = pd.to_datetime(df2.index)
DF1:
x
dat
2016-01-01 1
2016-01-02 2
2016-01-03 3
2017-01-01 4
2017-01-02 5
2017-01-03 6
DF2:
y
dat
2016-01-01 10
2017-01-01 11
我想只用年份和月份該指數的部分加入他們的行列。 所以輸出將類似於以下內容:
DF3:
x y
dat
2016-01-01 1 10
2016-01-02 2 10
2016-01-03 3 10
2017-01-01 4 11
2017-01-02 5 11
2017-01-03 6 11
我試圖使用
df1.join(df2, how='inner')
加入他們,我知道我可以提取年份和月份部分,像這樣:
df1.index.map(lambda x: x.strftime('%Y-%m'))
df2.index.map(lambda x: x.strftime('%Y-%m'))
但我不知道如何結合所有這些以達到預期效果?
非常感謝
太好了,謝謝您的解釋! – olyashevska