[英]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 ![]() |
45 ![]() |
Joe![]() |
563 ![]() |
13 ![]() |
Nick![]() |
24 ![]() |
|
Nick![]() |
45 ![]() |
155 ![]() |
Alice![]() |
188 ![]() |
34 ![]() |
Alice![]() |
43 ![]() |
|
Kate![]() |
43543 ![]() |
|
Kate![]() |
232 ![]() |
And the result should be:结果应该是:
Name![]() |
Life![]() |
Score![]() |
---|---|---|
Joe![]() |
789 ![]() |
45 ![]() |
Joe![]() |
563 ![]() |
13 ![]() |
Nick![]() |
45 ![]() |
24 ![]() |
Nick![]() |
45 ![]() |
155 ![]() |
Alice![]() |
188 ![]() |
34 ![]() |
Alice![]() |
188 ![]() |
43 ![]() |
Kate![]() |
43543 ![]() |
|
Kate![]() |
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.