通过特定值填充缺失值Pandas Dataframe [英] Filling Missing values Pandas Dataframe by specific value
本文介绍了通过特定值填充缺失值Pandas Dataframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据集,我想用bfill并在其中添加一个字符串来填充"value"列中的缺失数据.这是我拥有的代码:
I have a dataset and I want to fill the missing data in the column 'value' with bfill with adding a string to it. Here is to code that I have:
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
'category': ['X', 'X', 'X', 'X', 'X', 'X', 'Y', 'Y', 'Y'],
'name': ['A','A', 'B','B','B','B', 'C','C','C'],
'other_value': [10, np.nan, np.nan, 20, 30, 10, 30, np.nan, 30],
'value': [1, np.nan, np.nan, 2, 3, 1, 3, np.nan, 3],
}
)
print(df)
def fillValue(g):
gNotNull = g.dropna()
wtAvg = str(gNotNull[0])+'5D'
return g.fillna(wtAvg)
ff=pd.DataFrame()
ff["value"] = df['value'].transform(fillValue)
ff
我从这段代码中得到的输出是:
The output that I am getting from this code is:
value
0
1
1
1.05D
2
1.05D
3
2
4
3
5
1
6
3
7
1.05D
8
3
我想要的输出是重新装满,看起来像这样:
the out put that I want is to get back filled and look something like this:
value
0
1
1
25D
2
35D
3
2
4
3
5
1
6
3
7
85D
8
3
如果有人可以提供帮助,我深表感谢. 谢谢
I appreciate if anyone can help. Thanks
推荐答案
IIUC
s=df.value.bfill()
s.loc[df.value.isnull()]=s.astype(int).astype(str)+'5D'
s
Out[771]:
0 1
1 25D
2 25D
3 2
4 3
5 1
6 3
7 35D
8 3
Name: value, dtype: object
这篇关于通过特定值填充缺失值Pandas Dataframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文