[英]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.