简体   繁体   English

根据另一列 Pandas,如果它们不为空,则用它们的邻居填充空单元格

[英]Fill the empty cells with their neighbours if they are not empty based on another column Pandas

Good afternoon,下午好,

What is the simplest way to replace empty values to another value in one column if the text in the another column is equal?如果另一列中的文本相同,将一列中的空值替换为另一个值的最简单方法是什么?

For example, we have the dataframe:例如,我们有 dataframe:

Name名称 Life生活 Score分数
Joe 789 789 45 45
Joe 563 563 13 13
Nick缺口 24 24
Nick缺口 45 45 155 155
Alice爱丽丝 188 188 34 34
Alice爱丽丝 43 43
Kate凯特 43543 43543
Kate凯特 232 232

And the result should be:结果应该是:

Name名称 Life生活 Score分数
Joe 789 789 45 45
Joe 563 563 13 13
Nick缺口 45 45 24 24
Nick缺口 45 45 155 155
Alice爱丽丝 188 188 34 34
Alice爱丽丝 188 188 43 43
Kate凯特 43543 43543
Kate凯特 232 232

Thanks for all help!感谢所有帮助!

You can do it like this:你可以这样做:

import numpy as np
import pandas as pd

df = pd.DataFrame({
    'Name': ['Joe', 'Joe', 'Nick', 'Nick', 'Alice', 'Alice', 'Kate', 'Kate'],
    'Life': [789.0, np.nan, np.nan, 45.0, 188.0, np.nan, np.nan, np.nan],
    'Score': [45, 13, 24, 155, 34, 43, 43543, 232]
})
print(df)

# output:
#     Name   Life  Score
# 0    Joe  789.0     45
# 1    Joe    NaN     13
# 2   Nick    NaN     24
# 3   Nick   45.0    155
# 4  Alice  188.0     34
# 5  Alice    NaN     43
# 6   Kate    NaN  43543
# 7   Kate    NaN    232


df['Life'] = df.groupby('Name')['Life'].transform('first')
print(df)

# output:
#     Name   Life  Score
# 0    Joe  789.0     45
# 1    Joe  789.0     13
# 2   Nick   45.0     24
# 3   Nick   45.0    155
# 4  Alice  188.0     34
# 5  Alice  188.0     43
# 6   Kate    NaN  43543
# 7   Kate    NaN    232

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

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