0
我想在遍歷行時更新某些列值,但花了很長時間。我使用itertuples()
而不是iterrows()
作爲建議here和here,我不能使用apply
函數,因爲我想在一次迭代中更新兩列。Python Pandas:在遍歷行時對DataFrame值進行一些更新
我將使用一個簡化的例子,因爲我的案例涉及10-ish多列,與下面的代碼無關。在這裏包括它們會使代碼看起來更糟糕。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0, 5, size=(90000, 4)),
columns=['Initial', 'A', 'B'])
df['code'] = list('KLMNOP' * 15000) # Adding column 'code'
df = df.sort_values('code') # Sorting the df by 'code'
df['Total'] = np.nan
然後,我想更新基礎上的A
和B
值列Initial
和Total
,然後也由以前行的Total
更新Initial
。 我的意思是,Total
被結轉到下一行的Initial
當電流code
等於前一行的code
def produce_total(init, a, b):
if a >= 2 and b >= 2:
return init + 1
return init
last_code = ''
last_total = -100
for row in df.itertuples():
# Print the current checkpoint
if(row.Index % 1000 == 0):
print row.Index
# Carry over the prev Total to current Initial
if last_code == row.code:
df.loc[row.Index, 'Initial'] = last_total
# Prepare the updated Initial value
# Because what is inside 'row' seems unaffected by the update
new_initial = df.loc[row.Index, 'Initial']
# Find Total and assign to the df
new_total = produce_total(
new_initial,
row.A,
row.B
)
df.loc[row.Index, 'Total'] = new_total
last_code = row.code
last_total = new_total
代碼跑了將近一個小時,但只能達到30000指數十歲上下。任何想法或建議爲另一個或兩個有效的方法來做到這一點?
或者,我還需要考慮其他方面(刪除一些列等)?
非常感謝!