简体   繁体   中英

Identify df column name_pandas

I have two dataframes df1 and df2. In the first row of df1 column 'attribute', I have a value like 'color'. In df2 I have a column named 'color' in this case. Basically the column from df2 takes as name, the value from df1 column attribute.

But the name of this column is dynamic meaning, I may have another attribute value in df1 like 'size' so that the name of df2 column becomes 'size'. I need to access in df2 this column for concatenation. Is there a way of doing that?

If the attributes in df1 are strings, you can simply use the standard syntax:

import pandas as pd

df1 = pd.DataFrame({'attribute': ['color', 'size', 'shape']})
df2 = pd.DataFrame({'color': ['blue', 'red'],
                    'size': [1, 10],
                    'shape': ['a', 'b']})

df2[df1.attribute[0]]
0    blue
1     red
Name: color, dtype: object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM