gpt4 book ai didi

python - pandas 将函数应用于多个列并创建多个列来存储结果

转载 作者:行者123 更新时间:2023-12-01 00:35:58 28 4
gpt4 key购买 nike

我有以下df

country    street           postcode    id
SA XX0 1
GB 17 abc road 2
BE 129 def street 127 3
US nan nan 4

我想计算国家街道邮政编码值的熵;默认情况下,空字符串或 NaN 将获取值 0.25

from entropy import shannon_entropy

vendor_fields_to_measure_entropy_on = ('country', 'vendor_name', 'town', 'postcode', 'street')

fields_to_update = tuple([key + '_entropy_val' for key in vendor_fields_to_measure_entropy_on])

for fields in zip(vendor_fields_to_measure_entropy_on, fields_to_update):
entropy_score = []

for item in df[fields[0]].values:
item_as_str = str(item)
if len(item_as_str) > 0 and item_as_str != 'NaN':
entropy_score.append(shannon_entropy(item_as_str))
else:
entropy_score.append(.25)

df[fields[1]] = entropy_score

我想知道最好的方法是什么,所以结果看起来像,

 country    street           postcode    id    
SA XX0 1
GB 17 abc road 2
BE 129 def street 127 3
US nan nan 4


country_entropy_val street_entropy_val postcode_entropy_val
0.125 0.25 0.11478697512328288
0.125 0.38697440929431765 0.25
0.125 0.39775073104910885 0.19812031562256
0.125 0.25 0.25

最佳答案

>>> fields = ['country', 'street', 'postcode']
>>> for col in fields:
... df[f'{col}_entropy'] = df[col].apply(lambda x: shannon_entropy(str(x)) if not pd.isna(x) else 0.25)
...

关于python - pandas 将函数应用于多个列并创建多个列来存储结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57758297/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com