简体   繁体   English

如何从给定特定元素的数据框中获取特定的列键?

[英]How to get specific column key from data frame given a particular element?

Consider the data frame 考虑数据帧

   c1   c2   c3  
0 a 3    4    2  
1 b 1    2    7  

say I want to know which column in row 1 has the element 7. how will I achieve it? 说我想知道第1行中的哪一列具有元素7。我将如何实现它? I am trying to achieve it using pandas. 我正在尝试使用熊猫来实现它。

If want get column of first value in row with index 1 : 如果要获取索引为1行中第一个值的列:

a = df.loc[1].eq(7).idxmax()
print (a)
c3

Explanation: 说明:

First select column with index by loc : 首先通过loc选择具有索引的列:

print (df.loc[1])
c1    4
c2    2
c3    7
Name: (1, b), dtype: int64

Compare with 7 : 7比较:

print (df.loc[1].eq(7))
c1    False
c2    False
c3     True
Name: (1, b), dtype: bool

and for c3 get index of max value, it means first True . 对于c3获得最大值的索引,它意味​​着第一个True

If row contains multiple values (here 7) and need all matched columns use boolean indexing : 如果row包含多个值(此处为7),并且需要所有匹配的列,请使用boolean indexing

a = df.loc[1].eq(7)
a = a.index[a].tolist()

Not sure exactly what output you're looking for, but I believe this will help. 不确定您要查找的输出是什么,但是我相信这会有所帮助。 I started by creating your dataframe. 我首先创建您的数据框。

df = pd.DataFrame({'c1':['3', '1'],
                   'c2':['4', '2'],
                   'c3':['2', '7']})

The following code reads like so: give me all the records where the column 'c3' equals 7. 下面的代码是这样的:给我所有“ c3”列等于7的记录。

df = df[df['c3'] == '7']

Output: 输出:

在此处输入图片说明

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

相关问题 如何从数据框中的字典列表中存储特定的键值 - How to store a particular key value from a list of dictionaries in a data frame 在python中,如何从任何列中存在特定字符串的数据框中获取行(字符串值) - In python,how to get the rows from a data frame where a particular string is present in any of the column (String value) 如何通过文件处理从给定的数据框列中获取唯一对? - How to get the unique pairs from the given data frame column with file handling? 如何从包含特定列中的特定字符串(多个)的 Pandas 数据框中删除行? - How to drop rows from pandas data frame that contains a particular string(multiple) in a particular column? 如何在给定的数据帧中划分列“位置”? - How to divide the column 'location' in given data frame? 如何从给定的json获取特定值 - How to get a particular value from the given json 如何使用 python 从 pandas 数据帧中获取特定值? - How to get specific values in from a pandas data frame using python? 如何从数据框中获取特定值,使用 pandas 绘制图形 - How to get specific values from data frame, using pandas to graph 我如何从 python 字典中获取特定的元素和键 - How can i get specific Element and key from python Dictionary 如何从包含特定列中的任何字符串的Pandas数据框中删除行 - How to Remove Rows from Pandas Data Frame that Contains any String in a Particular Column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM