Python 从 Pandas 的索引中检索列的名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43068412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve name of column from its Index in Pandas
提问by Jatin Bhola
I have a pandas dataframe and a numpy array of values of that dataframe. I have the index of a specific column and I already have the row index of an important value. Now I need to get the column name of that particular value from my dataframe.
我有一个 Pandas 数据框和一个该数据框的 numpy 值数组。我有一个特定列的索引,我已经有了一个重要值的行索引。现在我需要从我的数据框中获取该特定值的列名。
After searching through the documentations, I found out that I can do the opposite but not what I want.
在搜索文档后,我发现我可以做相反的事情,但不是我想要的。
回答by jezrael
I think you need index columns names by position (python counts from 0
, so for fourth column need 3
):
我认为您需要按位置索引列名称(python 从 开始计数0
,因此对于第四列需要3
):
colname = df.columns[pos]
Sample:
样本:
df = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
print (df)
A B C D E F
0 1 4 7 1 5 7
1 2 5 8 3 3 4
2 3 6 9 5 6 3
pos = 3
colname = df.columns[pos]
print (colname)
D
pos = [3,5]
colname = df.columns[pos]
print (colname)
Index(['D', 'F'], dtype='object')