[英]merging two dataframes with same rows and indexes in pandas
我正在嘗試合並兩個具有共同行索引和共同列 0,1,2 但不同列 3 的 Pandas 數據幀,因此生成的數據幀具有來自兩者的列:
第一個數據框:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 817 entries, 0 to 816
Data columns (total 3 columns):
0 817 non-null int64
1 817 non-null int64
2 817 non-null float64
dtypes: float64(1), int64(2)
memory usage: 19.2 KB
0 1 2
0 1950 1 -0.060310
1 1950 2 0.626810
2 1950 3 -0.008128
3 1950 4 0.555100
4 1950 5 0.071577
第二個數據框:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 817 entries, 0 to 816
Data columns (total 3 columns):
0 817 non-null int64
1 817 non-null int64
2 817 non-null float64
dtypes: float64(1), int64(2)
memory usage: 19.2 KB
0 1 2
0 1950 1 0.92
1 1950 2 0.40
2 1950 3 -0.36
3 1950 4 0.73
4 1950 5 -0.59
到目前為止,我嘗試過合並:
pd.merge(df, df2, left_index=True, right_index=True, how='outer')
但結果並不是我所期望的:
0_x 1_x 2_x 0_y 1_y 2_y
0 1950 1 -0.060310 1950 1 0.92
1 1950 2 0.626810 1950 2 0.40
2 1950 3 -0.008128 1950 3 -0.36
3 1950 4 0.555100 1950 4 0.73
4 1950 5 0.071577 1950 5 -0.59
並使用連接:
pd.concat([df, df2], axis=1, ignore_index=True).head()
0 1 2 3 4 5
0 1950 1 -0.060310 1950 1 0.92
1 1950 2 0.626810 1950 2 0.40
2 1950 3 -0.008128 1950 3 -0.36
3 1950 4 0.555100 1950 4 0.73
4 1950 5 0.071577 1950 5 -0.59
我期待像
0 1 2 3
0 1950 1 -0.060310 0.92
1 1950 2 0.626810 0.40
2 1950 3 -0.008128 -0.36
3 1950 4 0.555100 0.73
4 1950 5 0.071577 -0.59
編輯:也許我不清楚,如果是這樣,我很抱歉,我試圖在結果中添加第二個數據集中的最后一列,所以我有相同的年、月、值1和值2列
我會嘗試:
pd.merge(df, df2, on=['0', '1'])
也許
pd.merge(df, df2, on=[0,1]
只需這樣做:
df.merge(df2, on=1)
一旦它們具有相同的索引,您就不需要添加索引列。 默認情況下,它可以是內部聯接。
您的錯誤是僅通過索引進行合並,合並函數不知道第 1 列在兩個數據中是否相等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.