簡體   English   中英

Python Pandas Dataframe 根據同一列中的前一行值計算新行值

[英]Python Pandas Dataframe calculating new row value based on previous row value within same column

這有點難以解釋,所以我將從我試圖使用 excel 實現的目標開始。

Excel示例

基本上,“Active”列的值基於同一行不同列值(“Act Count”和“De Count”列)的值,以及“Active”列的前一行中的值。

從 excel 公式中,如果 'Act Count' < 4 和 'De Count' < 4,則 'Active' = 前一行的 'Active' 值。

我想將其轉換為 Python pandas 數據框。

這是示例數據:

import pandas as pd

df = pd.DataFrame({'Act Count':[1,2,3,4,0,0,0,0,0,0,0,0,0,0],
              'De Count':[0,0,0,0,0,0,0,0,1,2,3,4,5,6]})

您可以假設第一行值 'Active' = 0。

我知道 .shift() 函數,但是我覺得我無法使用它,因為我無法移動尚不存在的列。

這不是一個優雅的解決方案,但它可以完成工作。

import pandas as pd

act_count = [1,2,3,4,0,0,0,0,0,0,0,0,0,0]
de_count = [0,0,0,0,0,0,0,0,1,2,3,4,5,6]

active = [0]
for i in range(1:len(act_count)):
    if act_count[i] >= 4:
       active.append(100)
    elif de_count[i] >= 4 :
       active.append(0)
    else:
       active.append(active[i-1])

df = pd.DataFrame({'Act Count': act_count, 'De Count' : de_count, 
              'Active' : active})

您可以使用此方法:

##Adding an empty column named Active to the existing dataframe
df['Active'] = np.nan

##putting the first value as 0
df['Active'].loc[0] = 0 

for index in range(1,df.shape[0]):
    if df['Act Count'].iloc[index]>=4:
        df['Active'].iloc[index]=100
    elif df['De Count'].iloc[index]>=4:
        df['Active'].iloc[index]=0
    else:
        df['Active'].iloc[index]=df['Active'].iloc[index-1]
print(df)

輸出:

   Act Count    De Count    Active
0   1           0           0.0
1   2           0           0.0
2   3           0           0.0
3   4           0           100.0
4   0           0           100.0
5   0           0           100.0
6   0           0           100.0
7   0           0           100.0
8   0           1           100.0
9   0           2           100.0
10  0           3           100.0
11  0           4           0.0
12  0           5           0.0
13  0           6           0.0

暫無
暫無

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

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