gpt4 book ai didi

python - Pandas 中的代码标准化和应用功能花费了太多时间

转载 作者:行者123 更新时间:2023-12-01 09:00:18 25 4
gpt4 key购买 nike

这只是我的代码的示例数据。我想标准化其他列中的总列。目前我有大约 2000 个组,标准化和 fgroup 需要 15 分钟。

有哪些方法可以减少时间。

import pandas as pd
import numpy as np

np.random.seed(1234)
n = 1500000

df = pd.DataFrame()
df['group'] = np.random.randint(1700, size=n)
df['ID'] = np.random.randint(5, size=n)
df['Total'] = np.random.randint(400, size=n)
df['Normalized_total'] = df.groupby('group')['Total'].apply(lambda x: (x-x.min())/(x.max()- x.min()))

def norm_group(df):
if df['Normalized_total'] > 0.70 and df['group'] > 100 and df['ID'] > 3:
return 3
elif df['Normalized_total'] > 0.5 and df['group'] < 100 and df['ID'] < 3:
return 2
else:
return 1

df['fgroup'] = df.apply(norm_group, axis=1)

谢谢

最佳答案

您可以使用transform并定义自己的函数

%timeit df['Normalized_total'] = df.groupby('group')['Total'].apply(lambda x: (x-x.min())/(x.max()- x.min()))
1 loop, best of 3: 508 ms per loop

# below is my solution
def myfunc():
g=df.groupby('group')['Total']
return df['Total']-g.transform('min')/g.transform(np.ptp)
%timeit myfunc()
1 loop, best of 3: 398 ms per loop

关于python - Pandas 中的代码标准化和应用功能花费了太多时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52503921/

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