简体   繁体   中英

How do I fill a column in ranges with values from the same column in Python?

I have dataframe df1:

col_1   col_2
A       a1
A       a2
B       
A       a3
C  
A       a4
A       a5
D
A       a6
A       a7
B

For non-empty values from col_2 , values from col_1 always have the value A . However, for empty values from col_2 , values from col_1 are always different from A , but they can repeat.

And I need output like:

col_1   col_2
B       a1
B       a2
C       a3
D       a4
D       a5
B       a6
B       a7

How can I do this? Thanks for the help.

Here is one way to do this:

mask = df.col_1 != 'A'

# Index col_1 based on the index of the mask's first true value
df.col_1 = df.col_1.iloc[[mask[i:].idxmax() for i in range(len(df))]].values

# Them simply drop the empty rows
df[~df.col_2.isnull()]

Output:

  col_1 col_2
0     B    a1
1     B    a2
3     C    a3
5     D    a4
6     D    a5
8     B    a6
9     B    a7

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