簡體   English   中英

Match one column's dataframe to another dataframe with a series of columns and extracting the columns header - Python

[英]Match one column's dataframe to another dataframe with a series of columns and extracting the columns header - Python

so, I have two dataframes and I'm attempting the match the column 'numbers' from dataframe 1 to the content of the full dataframe 2, and extract the column header and use that as a label/new column in dataframe 1. Struggling to不過為此建立一個管道。 我在 Python 工作。

dataframe 1

數字
100
101
102
103
200
201
202
203
300
301
302
303

dataframe 2:

建造 字段 盤子
100 200 300
101 201 301
102 202 302
103 203 303

output [與從 dataframe 2 匹配的新列 label]:

數字 label
100 建造
101 建造
102 建造
103 建造
200 字段
201 字段
202 字段
203 字段
300 盤子
301 盤子
302 盤子
303 盤子

使用melt壓平您的第二個 dataframe 然后merge其與您的第一個 dataframe 合並:

>>> df1.merge(df2.melt(var_name='label', value_name='numbers'), on='numbers')
    numbers         label
0       100  construction
1       101  construction
2       102  construction
3       103  construction
4       200        fields
5       201        fields
6       202        fields
7       203        fields
8       300        plates
9       301        plates
10      302        plates
11      303        plates

melt后,您的第二個 dataframe 看起來像:

>>> df2.melt(var_name='label', value_name='numbers')
           label  numbers
0   construction      100
1   construction      101
2   construction      102
3   construction      103
4         fields      200
5         fields      201
6         fields      202
7         fields      203
8         plates      300
9         plates      301
10        plates      302
11        plates      303

map的另一種方法:

df1['label'] = df1['numbers'].map(df2.melt().set_index('value').squeeze())
print(df)

# Output
    numbers         label
0       100  construction
1       101  construction
2       102  construction
3       103  construction
4       200        fields
5       201        fields
6       202        fields
7       203        fields
8       300        plates
9       301        plates
10      302        plates
11      303        plates

暫無
暫無

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

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