簡體   English   中英

Pandas:如何使用現有列和新創建列中的先前行創建新列?

[英]Pandas : How can I create new column using previous rows from existing column and newly created column?

從 excel 開始,我使用此公式創建新列(列 'D' )

IF(OR(A2<>A1,AND(B2<>"000",B1="000")),D1+1,0)

我已將現有 A 列和 B 列的前一行的數據作為在 D 列的當前行中創建值的條件,並且我已將 D 列的前一列值引用為當前單元格的數據。

如果 A 列和 B 列的數據符合我的標准,那么我將通過將 D 列的先前數據增加 1 來設置 D 列的當前行,否則我將 D 列的當前行重置為 0。

我嘗試在 pandas (python) 中執行此操作,但我無法實現。

那么有什么推薦嗎? 謝謝你。

我的excel中的例子

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

抱歉,我剛剛找到了這個鏈接,它可以幫助我。 這段代碼是我的解決方案。

import pandas as pd
import numpy as np

df = pd.read_csv(r'C:\sample.csv', dtype=str)

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

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

df

for index in range(1,df.shape[0]):  
    if ( (df['SERIAL_NUMBER'].iloc[index] !=  df['SERIAL_NUMBER'].iloc[index-1]) | 
        (df['OPERATION'].iloc[index] != '000') & (df['OPERATION'].iloc[index-1] == '000') ):
        df['answer'].iloc[index]=df['answer'].iloc[index-1]+1
    else:
        df['answer'].iloc[index]=df['answer'].iloc[index-1]
print(df)

暫無
暫無

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

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