簡體   English   中英

Python,在這種情況下用什么代替提示行?

[英]Python, what to use instead of itterrows in this case?

我試圖加快我的程序的速度,對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%。

從您的解釋中我無法確定您到底想要實現什么。 我認為

  • 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)

希望這會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM