'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:
| 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!
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
