행을 반복 할 때 일부 열 값을 업데이트하고 싶지만 오랜 시간이 걸립니다. 제안 된 here과 here과 같이 대신 itertuples()
을 사용하고, 하나의 반복에서 두 개의 열을 업데이트하고자하므로 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
현재 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
같은 경우 다음 행의 Initial
이월,하지만 지수 30000 틱에 도달하고, 의미한다. 이 작업을 수행하는 또 다른 또는 두 가지 효율적인 방법에 대한 아이디어 또는 제안?
또는 고려해야 할 다른 측면이 있습니다 (일부 열 제거 등)?
고맙습니다.