[英]Python Pandas replace NaN in one column with value from a row below of another column
name姓名 | ID ID | gender性别 |
---|---|---|
John约翰 | 123 123 | male男性 |
Scot苏格兰人 | na呐 | na呐 |
124 124 | male男性 | na呐 |
Jill吉尔 | 231 231 | female女性 |
I want to cut the missing values for "Scot" from the below and paste them instead of the "nan" values so the new dataframe will be thus:我想从下面删除“Scot”的缺失值并粘贴它们而不是“nan”值,因此新的 dataframe 将是:
name姓名 | ID ID | gender性别 |
---|---|---|
John约翰 | 123 123 | male男性 |
Scot苏格兰人 | 124 124 | male男性 |
Jill吉尔 | 231 231 | female女性 |
I think you're looking for bfill
.我认为您正在寻找bfill
。
Here's example: https://www.geeksforgeeks.org/python-pandas-series-bfill/这是示例: https://www.geeksforgeeks.org/python-pandas-series-bfill/
So this should do it:所以应该这样做:
df['ID'] = df['ID'].bfill()
df['gender'] = df['gender'].bfill()
or, if you don't need to be selective, you can run it on the entire dataframe:或者,如果您不需要选择性,您可以在整个 dataframe 上运行它:
df = df.bfill()
It might be easier to fix that, by changeing the way you originally load the data, because it seems you have a linebreak there.通过更改最初加载数据的方式可能更容易解决这个问题,因为那里似乎有换行符。 However you could do something like this:但是,您可以执行以下操作:
Test data:测试数据:
import pandas as pd
import numpy as np
df = pd.DataFrame({'name': {0: 'John', 1: 'Scot', 2: '124', 3: 'Jill'},
'ID': {0: '123', 1: np.nan, 2: 'male', 3: '231'},
'gender': {0: 'male', 1: np.nan, 2: np.nan, 3: 'female'}})
Code:代码:
# find out which rows are valid (m) and which contain the offset data (m2)
m = df['ID'].isna()
m2 = m.shift(fill_value=False)
# create a separate dataframe, only containing the relevant row and columns for filling nan values
df2 = df[df.columns[:-1]][m2].copy()
# harmonize the index and column names so it fits the original dataframe
df2.columns = df.columns[1:]
df2.index = df2.index-1
# fill empty values by using the newly created dataframe values
df.fillna(df2)[~m2]
Output: Output:
# name ID gender
# 0 John 123 male
# 1 Scot 124 male
# 3 Jill 231 female
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.