Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - how to collapse columns in pandas on null values?

Suppose I have the following dataframe:

pd.DataFrame({'col1':    ["a", "a", np.nan, np.nan, np.nan],
            'override1': ["b", np.nan, "b", np.nan, np.nan],
            'override2': ["c", np.nan, np.nan, "c", np.nan]})


    col1    override1   override2
0     a        b          c
1     a       NaN        NaN
2     NaN      b         NaN
3     NaN     NaN         c
4     NaN     NaN         NaN

Is there a way to collapse the 3 columns into one column, where override2 overrides override1, which overrides col1, however, in case there is NaN, then the values bofore is to be kept? Also, I am mainly looking for a way where I would not have to make an additional column. I am really looking for a built-in pandas solution.

This is the output I am looking for:

 collapsed
0  c
1  a
2  b
3  c
4  NaN
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

using ffill

df.ffill(1).iloc[:,-1]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...