我有缺少值的数据帧:
import pandas as pd
data = {'Brand':['residential','unclassified','tertiary','residential','unclassified','primary','residential'],
'Price': [22000,25000,27000,"NA","NA",10000,"NA"]
}
df = pd.DataFrame(data, columns = ['Brand', 'Price'])
print (df)
产生了这个数据框:
Brand Price
0 residential 22000
1 unclassified 25000
2 tertiary 27000
3 residential NA
4 unclassified NA
5 primary 10000
6 residential NA
我想用固定值填充价格列中缺少的住宅和未分类的值(住宅=1000,unclassified=2000),但是我不想丢失住宅或未分类的价格列中已经存在的任何值,因此输出应如下所示:
Brand Price
0 residential 22000
1 unclassified 25000
2 tertiary 27000
3 residential 1000
4 unclassified 2000
5 primary 10000
6 residential 1000
做这件事最简单的方法是什么?
发布于 2020-06-08 00:43:48
我们可以使用fillna
和PS进行map
:您需要确保在您的df中,NA是NaN
df.Price.fillna(df.Brand.map({'residential':1000,'unclassified':2000}),inplace=True)
df
Brand Price
0 residential 22000.0
1 unclassified 25000.0
2 tertiary 27000.0
3 residential 1000.0
4 unclassified 2000.0
5 primary 10000.0
6 residential 1000.0
https://stackoverflow.com/questions/62248518
复制相似问题