gpt4 book ai didi

python - 加速涉及多个数据帧的 Pandas 操作

转载 作者:行者123 更新时间:2023-11-28 18:14:56 25 4
gpt4 key购买 nike

大家好

对于一个学校项目,我对 Pandas Dataframe 的操作持续时间感到困惑。

我有一个数据框 df,其形状为 (250 000 000, 200)。该数据框包含描述机器上传感器行为的变量值。 它们按“循环”组织(每次机器开始一个新循环时,此变量都会递增 1)。在这个循环中,“CycleTime”描述了行在“Cycle”中的位置。

在“均值”DataFrame 中,我通过“CycleTime”计算每个变量组的均值

'anomaly_matrix' DataFrame 表示每个周期的全局异常,它是属于该周期的每一行的平方差与相应周期时间的平均值的平方和。

下面是我的代码示例

df = pd.DataFrame({'Cycle': [0, 0, 0, 1, 1, 1, 2, 2], 'CycleTime': [0, 1, 2, 0, 1, 2, 0, 1], 'variable1': [0, 0.5, 0.25, 0.3, 0.4, 0.1, 0.2, 0.25], 'variable2':[1, 2, 1, 1, 2, 2, 1, 2], 'variable3': [100, 5000, 200, 900, 100, 2000, 300, 300]})
mean = df.drop(['Cycle'], axis = 1).groupby("CycleTime").agg('mean')
anomali_matrix = df.drop(['CycleTime'], axis = 1).groupby("Cycle").agg('mean')
anomaly_matrix = anomali_matrix - anomali_matrix

for index, row in df.iterrows():
cycle = row["Cycle"]
time = row["CycleTime"]
anomaly_matrix.loc[cycle] += (row - mean.loc[time])**2


>>>anomaly_matrix
variable1 variable2 variable3
Cycle
0 0.047014 0.25 1.116111e+07
1 0.023681 0.25 3.917778e+06
2 0.018889 0.00 2.267778e+06

我的 (250 000 000, 200) DataFrame 的计算持续了 6 个小时,这是由于 anomaly_matrix.loc[cycle] += (row - mean.loc[time])**2

我试图通过使用应用函数来改进,但我没有成功地在该应用函数中添加其他 DataFrame。尝试矢量化 Pandas 也是同样的事情。

您知道如何加速这个过程吗?谢谢

最佳答案

您可以使用:

df1 = df.set_index(['Cycle', 'CycleTime'])

mean = df1.sub(df1.groupby('CycleTime').transform('mean'))**2
df2 = mean.groupby('Cycle').sum()
print (df2)
variable1 variable2 variable3
Cycle
0 0.047014 0.25 1.116111e+07
1 0.023681 0.25 3.917778e+06
2 0.018889 0.00 2.267778e+06

关于python - 加速涉及多个数据帧的 Pandas 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48948534/

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