簡體   English   中英

熊貓:將函數應用於特定的行值和索引

[英]Pandas: Apply function to specific row values and indexes

我正在嘗試編寫一個函數來將新變量計算到新列中。 我有一個數據集,可以跟蹤許多天的多個主題的變量。

Date        Athlete  Load
2016-01-04  Alan     180
2016-01-04  Ben      61
2016-01-04  David    186
2016-01-04  Joe      99
2016-01-04  John     131

我已經能夠按名稱過濾主題並為每個主題創建新的數據框。

for athlete in df['Athlete'].unique():
    athlete = df.loc[ewma['Athlete'] == athlete]
    print(athlete.head())

我遇到的問題是計算新列的公式。 根據第一個測量變量計算出第一個值,但是每個后續值都使用前一天的值。

例如,新列的第一行將使用:

x = (df['Load'].iloc[0] * 2) - (df['Load'].iloc[0] / 2)

x = 180

第二行將使用前一天的值(x)代替第二個df ['Load']值。 我能夠使用基本功能正確計算第二個值:

y = (df['Load'].iloc[1] * 2) - (x / 2)

y = 168

我嘗試使用“ if / else”,但未計算正確的值。

if df.index.name == '0':
    (df['Load'].iloc[0] * 2) - (df['Load'].iloc[0] / 2)
else:
     (df['Load'] * 2) - (df['Load'].shitf(-1) / 2)

任何建議將不勝感激。

應該這樣做:

def update_row(df):
    row_tmp = {"next_row": None}
    def updater(row):
        last_row_id = row.name - 1
        if row.name == 0:
            row_tmp['next_row'] = (row['Load'] * 2) - (row['Load'] /2.0)
            return row_tmp['next_row']
        row_tmp['next_row'] = (2* row['Load']) - (row_tmp['next_row']/2.0)
        return row_tmp['next_row']
    return updater


df

Date    Athlete Load
0   2016-01-04  Alan    180
1   2016-01-04  Alan    0
2   2016-01-04  Alan    123
3   2016-01-04  Alan    71
4   2016-01-04  Alan    137
5   2016-01-04  Alan    0
6   2016-01-04  Alan    0


df.apply(update_row(df), axis=1)

0    270.00000
1   -135.00000
2    313.50000
3    -14.75000
4    281.37500
5   -140.68750
6     70.34375
dtype: float64

PS,我相信您對x和y的計算不准確,根據您的公式,x應該為270,y應該為-13!

如果要排除第一行,然后:

previous_row = next_row * 2 - previous_row/2

可以這樣實現:

"""
(row n-1) = (row n) * 2 -  (row n-1) /2  except for row0.
"""
import pandas as pd 
df = pd.read_csv('data.txt',delim_whitespace=True)

df['new'] = df.Load * 2 - df.Load.shift(1)/2
df.loc[0,'new'] = df.Load[0]
df

結果是:

    Date        Athlete Load    new
0   2016-01-04  Alan    180     180.0
1   2016-01-04  Ben     61      32.0
2   2016-01-04  David   186     341.5
3   2016-01-04  Joe     99      105.0
4   2016-01-04  John    131     212.5

暫無
暫無

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

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