簡體   English   中英

在 python 中合並兩個 pandas 數據幀

[英]Merge two pandas Dataframes in python

嗨,我有兩個 pandas 數據幀。

數據1

播放器 1 2 3
p1 價值1 價值2 價值6
p2 價值1 價值6 價值7
p3 價值1 價值8 價值9
p4 價值6 價值6 價值6

數據2

1 2 3
價值1 價值8 價值6

我想合並它們,所以我讓這張表進一步工作

合並

播放器 1 2 3
p1 1 0 1
p2 1 0 0
p3 1 1 0
p4 0 0 1

你有什么主意嗎?

無需連接 - 只需直接比較值:

for i in data1.columns[1:]:
    data1[i] = (data1[i] == data2.iloc[0].loc[i]).astype('int')

print(data1)
  Player  1  2  3
0     p1  1  0  1
1     p2  1  0  0
2     p3  1  1  0
3     p4  0  0  1

另一種方法是復制data2中的行並與data1進行比較:

data1[data1.columns[1:]] = (
    data1[data1.columns[1:]] == pd.concat([data2]*data1.shape[1]).reset_index(drop=True)
).astype('int')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM