![](/img/trans.png)
[英]python / pandas - Find common columns between two dataframes, and create another one with same columns showing their difference
[英]find difference between any two columns of dataframes with a common key column pandas
我有兩個數據框,其中一個
Title Name Quantity ID
作為列
而第二個數據幀具有
ID Quantity
作為行數少於第一個數據框的列。
我需要根據ID列中的匹配關系找到兩個數據框的數量之間的差異,並將此差異存儲在第一個數據框中的單獨列中。
我嘗試了這個(沒用):
DF1[['ID','Quantity']].reset_index(drop=True).apply(lambda id_qty_tup : DF2[DF2.ID==asin_qty_tup[0]].quantity - id_qty_tup[1] , axis = 1)
另一種方法是應用DF1的ID和數量並遍歷DF2的每一行,但這需要更多時間。 我肯定有更好的方法。
您可以執行索引對齊的減法,大熊貓負責其余的工作。
df['Diff'] = df.set_index('ID').Quantity.sub(df2.set_index('ID').Quantity).values
演示版
在這里,changetype是索引,並且我已經設置了索引,因此pd.Series.sub
將默認對齊減法。 否則,您需要如上所述設置索引。
df1
strings test
changetype
0 a very -1.250150
1 very boring text -1.376637
2 I cannot read it -1.011108
3 Hi everyone -0.527900
4 please go home -1.010845
5 or I will go 0.008159
6 now -0.470354
df2
strings test
changetype
0 a very very boring text 0.625465
1 I cannot read it -1.487183
2 Hi everyone 0.292866
3 please go home or I will go now 1.430081
df1.test.sub(df2.test)
changetype
0 -1.875614
1 0.110546
2 -1.303974
3 -1.957981
4 NaN
5 NaN
6 NaN
Name: test, dtype: float64
在這種情況下,您可以使用map
:
df['diff'] = df['ID'].map(df2.set_index('ID').Quantity) - df.Quantity
import pandas as pd
df = pd.DataFrame({'Title': ['A', 'B', 'C', 'D', 'E'],
'Name': ['AA', 'BB', 'CC', 'DD', 'EE'],
'Quantity': [1, 21, 14, 15, 611],
'ID': ['A1', 'A1', 'B2', 'B2', 'C1']})
df2 = pd.DataFrame({'Quantity': [11, 51, 44],
'ID': ['A1', 'B2', 'C1']})
我們將使用df2
創建一個字典,該字典可用於將ID
映射到Quantity
。 因此,在df
任何有ID==A1
,它都被分配了數量11, B2
被分配了51,而C1
被分配了44。在這里,我僅出於說明目的將其添加為另一列。
df['Quantity2'] = df['ID'].map(df2.set_index('ID').Quantity)
print(df)
ID Name Quantity Title Quantity2
0 A1 AA 1 A 11
1 A1 BB 21 B 11
2 B2 CC 14 C 51
3 B2 DD 15 D 51
4 C1 EE 611 E 44
Name: ID, dtype: int64
然后,您可以減去df['Quantity']
和我們剛剛創建的列以得到差值。 (或者,如果需要其他差異,請從df['Quantity']
減去該值)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.