我有多个简单的函数需要在我的数据框的某些列的每一行上实现。数据框非常像,超过 1000 万行。我的数据框是这样的:
Date location city number value
12/3/2018 NY New York 2 500
12/1/2018 MN Minneapolis 3 600
12/2/2018 NY Rochester 1 800
12/3/2018 WA Seattle 2 400
我有这样的功能:
def normalized_location(row):
if row['city'] == " Minneapolis":
return "FCM"
elif row['city'] == "Seattle":
return "FCS"
else:
return "Other"
然后我使用:
df['Normalized Location'] =df.apply (lambda row: normalized_location (row),axis=1)
这非常慢,我怎样才能使它更有效率?
最佳答案
我们可以使用带有 defaultdict
的 map
使这个 BLAZING 变得更快。
from collections import defaultdict
d = defaultdict(lambda: 'Other')
d.update({"Minneapolis": "FCM", "Seattle": "FCS"})
df['normalized_location'] = df['city'].map(d)
print(df)
Date location city number value normalized_location
0 12/3/2018 NY New York 2 500 Other
1 12/1/2018 MN Minneapolis 3 600 FCM
2 12/2/2018 NY Rochester 1 800 Other
3 12/3/2018 WA Seattle 2 400 FCS
...出于性能原因,绕过 fillna
调用。这种方法很容易推广到多个替换。
关于python - 用缺失键的默认值替换 pandas 列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53602116/