[英]How do I fill a column in ranges with values from the same column in Python?
I have dataframe df1:我有 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
.对于
col_2
中的非空值, col_1
中的值始终具有值A
。 However, for empty values from col_2
, values from col_1
are always different from A
, but they can repeat.但是,对于
col_2
中的空值, col_1
中的值始终与A
不同,但它们可以重复。
And I need output like:我需要 output 像:
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: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.