简体   繁体   English

识别 df 列 name_pandas

[英]Identify df column name_pandas

I have two dataframes df1 and df2.我有两个数据框 df1 和 df2。 In the first row of df1 column 'attribute', I have a value like 'color'.在 df1 列“属性”的第一行中,我有一个像“颜色”这样的值。 In df2 I have a column named 'color' in this case.在 df2 中,我有一个名为“颜色”的列。 Basically the column from df2 takes as name, the value from df1 column attribute.基本上来自 df2 的列作为名称,来自 df1 列属性的值。

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'.但是这个列的名称是动态的意思,我可能在df1中有另一个属性值,比如'size',这样df2列的名称就变成了'size'。 I need to access in df2 this column for concatenation.我需要在 df2 中访问此列以进行连接。 Is there a way of doing that?有没有办法做到这一点?

If the attributes in df1 are strings, you can simply use the standard syntax:如果df1中的属性是字符串,则可以简单地使用标准语法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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