[英]How to select rows where date is in index in Python Pandas DataFrame?
[英]How to find the rows that do NOT share a common date (or index) in a Python dataframe
我有兩個熊貓數據框,每個數據框都有一個日期列。 我需要找到沒有共同日期的行
假設我在date列上創建了一個索引,有一些解決方案可以像這樣查找具有公共索引的行,但是我找不到任何優雅的解決方案來查找沒有公共日期的行。 例如df1
values 1
28/11/2000 -0.055276
29/11/2000 0.027427
30/11/2000 0.066009
01/12/2000 0.012749
04/12/2000 0.113892
DF2
values 2
24/11/2000 -0.004808
27/11/2000 -0.001812
28/11/2000 -0.026316
29/11/2000 0.015222
30/11/2000 -0.024480
給出兩個數據框:一個包含df1中沒有共同日期的行
DF11
value 1
01/12/2000 0.012749
04/12/2000 0.113892
另一個包含df2中不具有共同日期df22的行
value 2
24/11/2000 -0.004808
27/11/2000 -0.001812
我也可以使用其他任何格式的輸出,例如,如果我們可以減少步數,則可以將兩個數據幀都輸出到一個數據幀中。
有一些解決方案可以像這樣查找彼此不相等的行,但隨后該行的每個元素必須相同。
任何人都可以幫忙找到一個優雅的解決方案。 謝謝你的投入
如果不重新編制索引,我將從每個df中獲取唯一的日期,然后使用這些日期來掩蓋另一個日期。 就像是
df1 = df1[~df1['date'].isin(df2['date'].unique())]
df2 = df2[~df2['date'].isin(df1['date'].unique())]
使用Index.difference
:
df11 = df1.loc[df1.index.difference(df2.index)]
print (df11)
values 1
01/12/2000 0.012749
04/12/2000 0.113892
df22 = df2.loc[df2.index.difference(df1.index)]
print (df22)
values 2
24/11/2000 -0.004808
27/11/2000 -0.001812
用numpy.setdiff1d
解決方案:
df11 = df1.loc[np.setdiff1d(df1.index, df2.index)]
df22 = df2.loc[np.setdiff1d(df2.index, df1.index)]
使用indicator
merge
有魔術
s=df1.merge(df2,left_index=True,right_index=True,indicator=True,how='outer')
df1_1=s.loc[s['_merge']=='left_only',['values1']]
df2_2=s.loc[s['_merge']=='right_only',['values2']]
df1_1
values1
01/12/2000 0.012749
04/12/2000 0.113892
df2_2
values2
24/11/2000 -0.004808
27/11/2000 -0.001812
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.