[英]Pandas Dataframe iterating over rows
這是數據集
import pandas as pd
d = {'Key':['A','A','A','A'],'Rank':[1,2,3,4],'col1': [15000,12000,6000,7000], 'col2': [15000,10000,0,0],'col4': [10000,10000,10000,10000],'col5': [0,0,0,0] }
df = pd.DataFrame(data=d)
df
我試圖用它可以采用的可能最大值填充“col5”。其中“Col1”定義其最大限制,“col2”顯示其當前值。 如果它適合最大值,則移至下一行。 它可以容納的值由'col4'決定。 請看下面的例子。
例子:
這是最終的數據集,它應該看起來像
下面是我試過的代碼
for index, row in df.iterrows():
#print(row['col1'], row['col2'])
if row['col1']>row['col2']:
if (row['col1']-row['col2'])<row['col2']:
row['col5']=row['col1']-row['col2']
else:
row['col5']=row['col2']
#return
print(row['col1'], row['col2'],row['col5'])
這應該做你的事情(用多個鍵更新):
import pandas as pd
d = {'Key': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], 'Rank': [1, 2, 3, 4, 1, 2, 3, 4],
'col1': [15000, 12000, 6000, 7000, 15000, 12000, 6000, 7000], 'col2': [15000, 10000, 0, 0, 15000, 10000, 0, 0],
'col4': [10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000], 'col5': [0, 0, 0, 0, 0, 0, 0, 0]}
df = pd.DataFrame(data=d)
print(df)
df_result = pd.DataFrame()
for group in df.groupby(df.Key):
tmp_value = 0
df_tmp = group[1]
for index, row in df_tmp.iterrows():
if tmp_value == 0:
tmp_value = row['col4']
# print(row['col1'], row['col2'])
if row['col1'] > row['col2']:
diff_value = row['col1'] - row['col2']
if diff_value < tmp_value:
df_tmp.at[index, 'col5'] = row['col1'] - row['col2']
tmp_value = tmp_value - diff_value
else:
df_tmp.at[index, 'col5'] = tmp_value
break
df_result = df_result.append(df_tmp)
print(df_result)
一些提示:
tmp_value 保存第 4 列的數據,隨着時間的推移而減少。
你應該打破break
,不與我的腦海里退出
在這里,您可以閱讀有關在迭代期間編輯熊貓行的信息: Update a dataframe in pandas while iterating row by row 。
編輯:您也可以先獲取關鍵數據並將“col4”數據保存在數組中並直接更改原始數據幀,但這取決於您
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.