簡體   English   中英

Python:使用取決於先前值的值填充數據框中的列

[英]Python: Populate column in data frame with a value that depends on the previous value

我需要找到一種簡潔的方法來使用如下代碼填充我的 dataframe:

x = 1
df.at[x,'col2']=df.at[x,'col1'] + df.at[x-1,'col2']
x = 2
df.at[x,'col2']=df.at[x,'col1'] + df.at[x-1,'col2']
x = 3
df.at[x,'col2']=df.at[x,'col1'] + df.at[x-1,'col2']
x = 4
df.at[x,'col2']=df.at[x,'col1'] + df.at[x-1,'col2']

...等等,直到最后幾行。 每行代碼都取決於上面的結果,所以我不確定它是否可以使用滾動 function? 我也嘗試過.shift(1)但也沒有成功。 基本上我需要計算上面從 x=1 到 x=last 列

以下面為例:

       col1         col2
0       0             0
1       1           value above (0) plus value from col1 (1) = 1
2       3           value above (1) plus value from col1 (3) = 4 

誰能幫忙?

一個快速的解決方案,可以通過使其通用來做得更好(這是特定於問題的)

import pandas as pd
d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df = pd.DataFrame(data=d)
print(df,"\n\n")
x = len(df)
df.iloc[1:,1] = df.iloc[1:x,0].values + df.iloc[0:x-1,1].values

print(df)

我使用 .values 來解決索引給出 NaN 的問題,並得到了遇到同樣問題的這篇文章的幫助。

這返回,

   col1  col2
0     1     4
1     2     5
2     3     6 


   col1  col2
0     1     4
1     2     6
2     3     8

暫無
暫無

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

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