简体   繁体   English

如何使用 Python 中同一列的值填充范围中的列?

[英]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.

相关问题 如何用同一列中已有的值填充列中的缺失值? - How do I fill missing values in a column with already existing values in the same column? Python:用从同一列中选取的随机值填充 dataframe 中的 NaN - Python: fill NaN in dataframe with random values picked from the same column python / excel:如何为列A中的所有相同值添加列B的值 - python/excel: How do I add values of column B for all the same values in column A 如何使用 python 以行列格式填充方框中的值以进行 tictaoe 游戏 - How do I fill values inside square boxes in row column format using python for a tictaoe game 如何用两个值的总和在特定列中填充 NA? - How do I fill NA in specific column with the sum of two values? 如何从python中的excel列打印字符串值? - How do I print string values from excel column in python? 如何用同一列中的值填充 null 列中的 Pyspark Dataframe 值,其在另一列中的对应值相同 - How to fill null values in a Pyspark Dataframe column with values from the same column, whose corresponding value in another column is same 如何在python中填写插入语句的列名 - How do I fill in the column names of an insert statement in python 如何在 python 的列中交换值 - How do I swap values in a column in python 在 pandas 中,如何根据一列中的唯一值创建列,然后根据另一列中的值填充它? - In pandas, how do I create columns out of unique values in one column, and then fill it based on values in another column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM