![](/img/trans.png)
[英]Filter a dataframe column for a keyword, return seperate column value (name) from the row where each keyword is found
[英]return the column name from a table where a specific value in any row were found with python and pandas
在一个表中有不同的值。 但是,其他行中的其他列中的值相同(第一=标题/列名):
|---------------------|------------------|------------------|
| A | B | C |
|---------------------|------------------|------------------|
| 100 | 200 | 300 |
|---------------------|------------------|------------------|
| 400 | 100 | 500 |
|---------------------|------------------|------------------|
| 600 | 700 | 800 |
|---------------------|------------------|------------------|
要打印具有特定值(例如100)的所有行,请使用以下python代码:
import pandas as pd
df = pd.read_excel('test.xlsx', sheet_name='test1')
dfObject = df[df.isin([100]).any(axis=1)]
print(dfObject)
重新产生这样的输出:
|---------------------|------------------|------------------|
| A | B | C |
|---------------------|------------------|------------------|
| 100 | 200 | 300 |
|---------------------|------------------|------------------|
| 400 | 100 | 500 |
|---------------------|------------------|------------------|
有什么办法可以只打印特定值所在的列名,如下所示(也可以有区别):
|---------------------|
| A |
|---------------------|
| B |
|---------------------|
IIUC,用途:
df.columns[df.eq(100).any()]
#Index(['A', 'B'], dtype='object')
要获得系列输出,请调用pd.Series()
: pd.Series(df.columns[df.eq(100).any()])
是的,只需使用这样的columns
属性:
df[df.isin([100]).any(axis=1)].columns
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.