简体   繁体   中英

return the column name from a table where a specific value in any row were found with python and pandas

In a table are different value. However there are equal values in other columns from other rows (First = Header/Column Name):

|---------------------|------------------|------------------|
|          A          |     B            |     C            |
|---------------------|------------------|------------------|
|          100        |     200          |     300          |
|---------------------|------------------|------------------|
|          400        |     100          |     500          |
|---------------------|------------------|------------------|
|          600        |     700          |     800          |
|---------------------|------------------|------------------|

To print all rows with a specific value like 100 i use following python code:

import pandas as pd

df = pd.read_excel('test.xlsx', sheet_name='test1')

dfObject = df[df.isin([100]).any(axis=1)]

print(dfObject)

reusulting in an output like this:

|---------------------|------------------|------------------|
|          A          |     B            |     C            |
|---------------------|------------------|------------------|
|          100        |     200          |     300          |
|---------------------|------------------|------------------|
|          400        |     100          |     500          |
|---------------------|------------------|------------------|

Is there any way to print only the column names where the specific value is in like this (also with distinct):

|---------------------|
|          A          |
|---------------------|
|          B          |
|---------------------|

IIUC, use:

df.columns[df.eq(100).any()]

#Index(['A', 'B'], dtype='object')

To Get output as series, call pd.Series() : pd.Series(df.columns[df.eq(100).any()])

是的,只需使用这样的columns属性:

df[df.isin([100]).any(axis=1)].columns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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