如何编写一个函数来处理字典类型 Serires 和 Dataframe 中的一列?

How to wright a function to work with dictionary type Serires and a column in Dataframe?

我正在尝试编写一个适用于 Series 和 Dataframe 的函数。

dct= {10: 0.5, 20: 2, 30: 3,40:4}
#Defining the function
def funtion_dict(row,dict1):
    total_area=row['total_area']
    if total_area.round(-1) in dict1:     
        return dict1.get(total_area.round(-1))*total_area

#checking function in a test situation
row = pd.DataFrame(
    {
        'total_area': [53, 14.8, 94, 77, 12],
        'b': [5, 4, 3, 2, 1],
        'c': ['X', 'Y', 'Y', 'Y', 'Z'],
    }
)

print(funtion_dict(row,dct))

我一直收到错误消息 'Series' 对象是可变的,因此无法对其进行散列处理'。请帮忙

这是预期的行为,因为您正在尝试使用“系列”来查找不允许的字典。

根据您的代码,

dct= {10: 0.5, 20: 2, 30: 3,40:4}
df = pd.DataFrame({
    'total_area': [53, 14.8, 94, 77, 12],
    'b': [5, 4, 3, 2, 1],
    'c': ['X', 'Y', 'Y', 'Y', 'Z'],
})

如果您想使用从字典中匹配的乘数向数据框添加另一列,您可以这样做:

df['new_column'] = df['total_area'].round(-1).map(dct) * df['total_area']

然后会给你

   total_area  b  c  new_column
0        53.0  5  X         NaN
1        14.8  4  Y         7.4
2        94.0  3  Y         NaN
3        77.0  2  Y         NaN
4        12.0  1  Z         6.0