[英]Pandas : How can I create new column using previous rows from existing column and newly created column?
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.