简体   繁体   English

Python 和 Pandas:如果键值匹配,则将值从非 NaN 单元格复制到 Nan 单元格

[英]Python and Pandas: copying values from non NaN cells to Nan Cells if key values match

I'm new to python and Pandas and I encountered this issue.我是 python 和 Pandas 的新手,我遇到了这个问题。

so, if I have 4 columns and some rows所以,如果我有 4 列和一些行

A.一种。 B. B. C. C。 D. D.
Q50. Q50。 12. 12. 34 34 xy xy
Q50. Q50。 23. 23. NaN.南。 NaN钠盐
Q52. Q52. 01. 01. 50. 50。 CAT

I want if A is matching (Q50 in row 1 and row 2) to copy all values from row 1 to row 2 (in this example) values to the NaN.如果 A 匹配(第 1 行和第 2 行中的 Q50),我想将所有值从第 1 行复制到第 2 行(在本例中)值到 NaN。

so I will have:所以我会有:

A.一种。 B. B. C. C。 D. D.
Q50. Q50。 12. 12. 34 34 xy xy
Q50. Q50。 23. 23. 34 34 xy xy
Q52. Q52. 01. 01. 50. 50。 CAT

I'm wondering if there is a way to use np.where() where I can say if column A's value exists in my dataframe (row 2 where I have NaNs and row 1 where all cells are filled) then set all NaN in row 2 to equal row 1.我想知道是否有一种方法可以使用 np.where() ,我可以说 A 列的值是否存在于我的 dataframe 中(我有 NaN 的第 2 行和所有单元格都已填充的第 1 行)然后将所有 NaN 设置为行2等于第1行。

EDIT ----- based on a request:编辑 ----- 根据要求:

when I run df.head().to_dict()当我运行 df.head().to_dict()

{'A': {0: Q50', 1: 'Q52' 2: 'Q50'}, 'B': {0: '12', 1: '01', 2: '23'}, 'C': {0:'34', 1: '50', 2: 'NaN'} 'D': {0: 'xy', 1: 'CAT', 2: 'NaN'}} {'A': {0: Q50', 1: 'Q52' 2: 'Q50'}, 'B': {0: '12', 1: '01', 2: '23'}, 'C' : {0:'34', 1: '50', 2: 'NaN'} 'D': {0: 'xy', 1: 'CAT', 2: 'NaN'}}

Use:利用:

df.groupby('A.').apply(lambda x: x.ffill())

or或者

df.groupby(df['A.'].values).ffill()

output: output:

     A.    B.    C.   D.
0  Q50.  12.0  34.0   xy
1  Q50.  23.0  34.0   xy
2  Q52.   1.0  50.0  CAT

NB.注意。 you can't do df.groupby('A.').ffill() directly as this loses the column 'A.'你不能直接执行df.groupby('A.').ffill()因为这会丢失列 'A.'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM