首页 > 解决方案 > Python,在这种情况下用什么代替 itterrows?

问题描述

我试图加快我的程序,我对 python 和 pandas 还很陌生,我只是用这段代码来看看它是否有效并且确实有效,但是有没有办法加快它。我知道 itterrows 非常慢,也许 .apply 函数更快,但是当我想使用其中的当前行位置时,我不知道如何使用它。也许你们中的一个可以帮助我。

这是我的代码:

for i, row in df.iterrows():
    if df.iloc[i, 2] == 1000:
        list = []
        datum = df.iloc[i, 0]
        id = df.iloc[i, 1]
        for j, row in df.iterrows():
            if df.iloc[j, 0] == datum:
                if df.iloc[j, 0] != id:
                    waarde = df.iloc[j, 2]
                    if waarde != 1000:
                        waarde2 = df.iloc[j-1, 2]
                        respectivelijk = waarde / waarde2
                        # print(waarde)
                        # print(waarde2)
                        # print(respectivelijk)
                        list.append(respectivelijk)
        # print(list)
        gem = sum(list) / len(list)
        # print(gem)
        # print(df.iloc[i-1, 2])
        correcte_waarde = (gem * df.iloc[i-1, 2])
        # print(correcte_waarde)
        df.set_value(i, 'water_level', correcte_waarde)

我的数据框如下所示: https ://gyazo.com/0fdce9cbac81562195e4f24d55eac9a9 我正在使用此代码将错误(值 1000)替换为基于其他对象值变化的值。例如,如果所有其他对象在丢失的一小时内上升 50%,我可以假设/估计丢失的值也会上升 50%。

标签: pythonpandas

解决方案


我无法从您的解释中看出您到底想要达到什么目的。我假设

  • 1) 您想查找Value(您必须在此处使用另一个名称...)的值所在的所有行equal to 1000,因为它表示读取错误。
  • 2)然后您想1000用更具代表性的东西替换 ,例如,通过使用插值。

我将从这两个假设出发。我用temp专栏来代表你的value专栏。

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

# seed for reproducibility
np.random.seed(seed=1111)

# generate a dataframe with random datetimes and values
date_today = datetime.now()
days = pd.date_range(date_today, date_today + timedelta(1000), freq='D')
data = np.random.randint(1, high=100, size=len(days))
df = pd.DataFrame({'the_date': days, 'temp': data})
df = df.set_index('the_date')

print(df)

# get all the indicies of the temp column where the value equals 23. Change it to 1000 for your data.
select_indices = list(np.where(df["temp"] == 23)[0])

# replace all values in the temp column that equal 23 with NAN. Change 23 to 1000 for your data.
df.loc[df['temp'] == 23] = np.nan

# interpolate the data and replace the NAN's
interpolated_df = df.interpolate(method='linear', axis=0).ffill().bfill()

# get the interpolated rows, just to see what values the NAN's were replaced with
interpolated_rows = interpolated_df.iloc[select_indices]

print(interpolated_rows)

希望这会有所帮助。


推荐阅读