Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

python - Pandas, list all the columns that have null values for each row

I have the following df:

mask = df.apply(lambda row: True if row.isnull().any() else False, axis=1)
df[HAS_MISSING_VALUES] = mask
         date      kpi1       kpi2      kpi3      location has_missing_values
0  2019-01-25      147.0      nan       82.876859   team1   True
1  2019-01-26      147.0      41.0      71.178657   team1   False
2  2019-01-27      nan        42.0      81.812117   team2   True
3  2019-01-28      147.0      42.0      75.754279   team2   False
4  2019-01-29      nan        42.0      nan         team4   True
5  2019-01-30      nan        nan       nan         team4   True

I need to create a new column that for each row contains its null values names.

so for example the output would be:

         date      kpi1       kpi2      kpi3      location missing_kpis
0  2019-01-25      147.0      nan       82.876859   team1  [kpi2]
1  2019-01-26      147.0      41.0      71.178657   team1  []
2  2019-01-27      nan        42.0      81.812117   team2  [kpi1]
3  2019-01-28      147.0      42.0      75.754279   team2  []
4  2019-01-29      nan        42.0      nan         team4  [kpi1,kpi3]
5  2019-01-30      nan        nan       nan         team4  [kpi1,kpi2,kpi3]

but been stuck from there

question from:https://stackoverflow.com/questions/65867918/pandas-list-all-the-columns-that-have-null-values-for-each-row

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is what I came up with, hope this answers your question

missing = []
for row in data.index:
  missing.append(list(data.iloc[row][data.iloc[row].isnull()].index))

data['Has_Missing_values'] = missing
print(data)

dataframe


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...