繁体   English   中英

遍历 pandas dataframe 中的行

[英]Iterate over rows in a pandas dataframe

例子:

在此处输入图像描述

我希望将 go 的现金剩余值转换为下一行的可用值,随后每隔一行转换一次,但我不确定如何 go 这样做。

从外观上看,您可以使用 pandas 应用并传递适当的 lambda function ,它将前一行的cash_remaining值作为参数,例如使用.iloc。

该方法取决于每个月是否有一些额外的逻辑:

from datetime import datetime as dt

import numpy as np
import pandas as pd


df = pd.DataFrame.from_dict({
    'date': [dt(2008, 4, 30), dt(2008, 5, 3), dt(2008, 6, 30), dt(2008, 7, 31), dt(2008, 8, 29)],
    'NYSEARCA:PYZ': [36.37, 38.52, 35.82, 35.80, 34.86],
    'amount_available': [2100] + [np.nan]*4,
    'amount_spent': [1984.2] + [np.nan]*4,
    'cash_remaining': [115.8] + [np.nan]*4
})


method_1 = df.copy()
# if there is "row-by-row" dependencies
for i, row in method_1.iterrows():
    if not np.isnan(row['cash_remaining']):
        cash_rem = row['cash_remaining']
    else:
        # dummy additional time-series dependent logic
        cash_rem_old = cash_rem
        spent = round(np.random.rand(1).item() * 20, 2) # whatever
        cash_rem = cash_rem_old - spent

        row[['amount_available', 'amount_spent', 'cash_remaining']] = [cash_rem_old, spent, cash_rem]
        method_1.iloc[i] = row

# if values just need to be copied over
method_2 = df.copy()
target = method_2['cash_remaining'][0]
method_2.loc[1:, ['amount_available', 'amount_spent', 'cash_remaining']] = [target, 0.0, target]

print(method_1)
#         date  NYSEARCA:PYZ  amount_available  amount_spent  cash_remaining
# 0 2008-04-30         36.37           2100.00       1984.20          115.80
# 1 2008-05-03         38.52            115.80         14.81          100.99
# 2 2008-06-30         35.82            100.99          0.96          100.03
# 3 2008-07-31         35.80            100.03         17.65           82.38
# 4 2008-08-29         34.86             82.38          7.24           75.14

print(method_2)
#         date  NYSEARCA:PYZ  amount_available  amount_spent  cash_remaining
# 0 2008-04-30         36.37            2100.0        1984.2           115.8
# 1 2008-05-03         38.52             115.8           0.0           115.8
# 2 2008-06-30         35.82             115.8           0.0           115.8
# 3 2008-07-31         35.80             115.8           0.0           115.8
# 4 2008-08-29         34.86             115.8           0.0           115.8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM