gpt4 book ai didi

python - Pandas 在迭代行时不保存更改

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:15 26 4
gpt4 key购买 nike

假设我有以下数据框:

射门进球 StG
0 1 2 0.5
1 3 1 0.33
2 4 4 1

现在我想将变量 Shots 乘以一个随机值(代码中的乘数)并重新计算 StG 变量,该变量只不过是 Shots/Goals,我使用的代码是:

for index,row in df.iterrows():
multiplier = (np.random.randint(1,5+1))
row['Shots'] *= multiplier
row['StG']=float(row['Shots'])/float(row['Goals'])

然后我保存了 .csv,它与原始文件完全相同,因此在 for 之后我只需使用 print(df) 来获取:

Shots Goals StG
0 1 2 0.5
1 3 1 0.33
2 4 4 1

如果我在 for 迭代期间每行打印值行,我会看到它们发生变化,但就像它们没有保存在 df 中一样。

我认为这是因为我只是访问值,而不是实际的数据帧。

我应该添加类似 df.row[] 的内容,但它返回 DataFrame 没有 row 属性。

感谢您的帮助。

____编辑____

for index,row in df.iterrows():
multiplier = (np.random.randint(1,5+1))
row['Impresions']*=multiplier
row['Clicks']*=(np.random.randint(1,multiplier+1))
row['Ctr']= float(row['Clicks'])/float(row['Impresions'])
row['Mult']=multiplier
#print (row['Clicks'],row['Impresions'],row['Ctr'],row['Mult'])

主要条件是点击次数不能高于展示次数。

然后我重新计算点击率/展示次数之间的比率。

我不确定将整个列相乘是否是维持每行 Impr >= Clicks 条件的最佳选择,因此我逐行进行

最佳答案

有关 iterrows() 的 pandas 文档:pandas.DataFrame.iterrows

“您永远不应该修改正在迭代的内容。这不能保证在所有情况下都有效。根据数据类型,迭代器返回一个副本而不是 View ,并且写入它不会有任何影响。效果。”

好消息是您不需要迭代行 - 您可以对列执行操作:

# Generate an array of random integers of same length as your DataFrame
multipliers = np.random.randint(1, 5+1, size=len(df))

# Multiply corresponding elements from df['Shots'] and multipliers
df['Shots'] *= multipliers

# Recalculate df['StG']
df['StG'] = df['Shots']/df['Goals']

关于python - Pandas 在迭代行时不保存更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43351036/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com