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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.