簡體   English   中英

將兩個數據框合並為一個具有標記為1或0的唯一項的新數據框

[英]Merging two data frames into a new one with unique items marked with 1 or 0

我有幾個數據幀。

數據幀#1

Feature   Coeff
a         0.5
b         0.3
c         0.35
d         0.2

數據幀#2

Feature   Coeff
a         0.7
b         0.2
y         0.75
x         0.1

我想合並此數據框並獲取以下數據:

Feature |  DF1  |  DF2
a          1       1
b          1       1
c          1       0
d          1       0
y          0       1
x          0       1

我知道我可以進行outer merge但我不知道如何從那里移動以獲得我上面提到的最終數據幀。 有任何想法嗎?

使用concat + get_dummies

u = pd.concat([df1, df2], axis=0, keys=['DF1', 'DF2'])

pd.get_dummies(u.Feature).sum(level=0).T

   DF1  DF2
a    1    1
b    1    1
c    1    0
d    1    0
x    0    1
y    0    1

您可以與series.str.get_dummies()一起使用merge來實現此目的:

m=df1[['Feature']].merge(df2[['Feature']],how='outer',indicator=True)

d={'both':'DF1,DF2','left_only':'DF1','right_only':'DF2'}
m=m.assign(_merge=m._merge.map(d))
m[['Feature']].join(m._merge.str.get_dummies(','))

  Feature  DF1  DF2
0       a    1    1
1       b    1    1
2       c    1    0
3       d    1    0
4       y    0    1
5       x    0    1

與user3483203相同的想法,但使用crosstab

u = pd.concat([df1, df2], axis=0, keys=['DF1', 'DF2'])


pd.crosstab(u.Feature, u.index.get_level_values(0))

我使用pd.merge合並了兩個數據幀,並使用列表pd.merge來分配值。

df = df1.merge(df2, on='Feature', how='outer')
df['DF1'] = [1 if x > 0 else 0 for x in df['Coeff_x']]
df['DF2'] = [1 if x > 0 else 0 for x in df['Coeff_y']]
df.drop(['Coeff_x', 'Coeff_y'], axis=1, inplace=True)

    Feature DF1 DF2
0   a   1   1
1   b   1   1
2   c   1   0
3   d   1   0
4   y   0   1
5   x   0   1

我已經看過其他 - 熊貓特定的 - 答案,我想問一下,如果你可以使用內置的方法/函數實現相同的方法,如series.str.get_dummies()有什么優點? 它快得多嗎? 真的好奇,因為我自己是新手。

(對不起,我需要更多的聲望點才能直接在其他答案下留下評論!)

暫無
暫無

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

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