[英]merge two dataframes pandas
我正在使用以下內容閱讀2 dfs:
extra = pd.read_csv('table1.txt', sep = '\s+')
data = pd.read_csv('table2.dat', sep = '\s+')
extra.info()
的輸出是:
class 'pandas.core.frame.DataFrame'>
Int64Index: 11528 entries, 0 to 11527
Data columns:
a 11528 non-null values
key 11528 non-null values
c 11528 non-null values
d 11528 non-null values
e 11528 non-null values
f 11528 non-null values
g 11528 non-null values
h 11528 non-null values
i 11528 non-null values
j 11528 non-null values
k 11528 non-null values
dtypes: float64(11)None
data.info()
的輸出是:
class 'pandas.core.frame.DataFrame'>
Int64Index: 11528 entries, 0 to 11527
Data columns:
1 11528 non-null values
2 11528 non-null values
3 11528 non-null values
key 11528 non-null values
5 11528 non-null values
...
79 11528 non-null values
80 11528 non-null values
81 11528 non-null values
dtypes: float64(80), int64(1)None
因此,這2個11528 rows
都具有11528 rows
並且它們具有稱為: key
的公共列
我使用以下方法合並了這2個df:
result = pd.merge(data, extra, on='key', sort = False)
並且result.info()
的輸出是:
class 'pandas.core.frame.DataFrame'>
Int64Index: 11926 entries, 0 to 11925
Data columns:
1 11926 non-null values
2 11926 non-null values
3 11926 non-null values
key 11926 non-null values
5 11926 non-null values
6 11926 non-null values
...
80 11926 non-null values
81 11926 non-null values
a 11926 non-null values
b 11926 non-null values
...
j 11926 non-null values
k 11926 non-null values
dtypes: float64(90), int64(1)None
顯然有問題,因為新合並的df result
有11926 rows
。
有人可以解釋發生了什么嗎?將其寫下來的正確方法是什么?
謝謝!
df1 = 1 key 3 4
1 8 90 5 11
2 7 60 2 30
3 3 70 3 26
4 7 60 2 10
df2 = 5 6 key 7
1 3 2 90 17
2 9 3 60 42
3 6 4 70 17
4 1 5 60 23
我想要的輸出是:
1 key 3 4 5 6 7
1 8 90 5 11 3 2 17
2 7 60 2 30 9 3 42
3 3 70 3 26 6 4 17
4 7 60 2 10 1 5 23
發生的情況是您在一個或兩個數據框中都有重復的key
值。 因此,如果data
在其中有5次key1
,而extra
在其中有2次key1
,那么當您合並key列上的兩個數據幀時, key1
會有10個條目。
解決方法是:
# delete the common column in one of the data frames
del extra['key']
# join
result = data.join(extra)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.