'identify the columns have specific value for each row in python
I'm newer at python. I have a dataframe like this
1 2 3
75016 1 2 2
75017 0 0 0
75018 0 2 2
For each row, I want to identify what the columns have the value = 1 or 2 the output =
" 75016 " has = column 1,2,3
" 75017 " has column
" 75018 " has column 2,3
how I can do it? thank you
Solution 1:[1]
Assuming a pandas DataFrame, you can use:
s = df.stack().isin([1,2])
out = (s[s]
.reset_index(1)
.groupby(level=0)['level_1']
.agg(','.join)
.reindex(df.index).fillna('')
)
output:
75016 1,2,3
75017
75018 2,3
Name: level_1, dtype: object
used input:
import pandas as pd
df = pd.DataFrame({'1': [1, 0, 0], '2': [2, 0, 2], '3': [2, 0, 2]},
index=[75016, 75017, 75018])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
