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