gpt4 book ai didi

python - 使用 loc 更新数据框 python pandas

转载 作者:太空狗 更新时间:2023-10-29 23:58:13 29 4
gpt4 key购买 nike

我有一个具有列结构的 Pandas 数据框(df):

month a b c d

此数据框包含一月、二月、三月、四月的数据。A、B、C、D 是数字列。对于 Feb 月份,我想重新计算 A 列并在数据框中更新它,即 month = Feb, A = B + C + D

我使用的代码:

 df[df['month']=='Feb']['A']=df[df['month']=='Feb']['B'] + df[df['month']=='Feb']['C'] + df[df['month']=='Feb']['D'] 

这运行没有错误,但没有更改 A 列中 2 月份的值。在控制台中,它给出了一条消息:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

我尝试使用 .loc,但现在我正在处理的数据框,我已经在其上使用了 .reset_index(),但我不确定如何设置索引和使用 .loc。我遵循了文档但不清楚。你能帮我一下吗?这是一个示例数据框:

 import pandas as pd import numpy as np
dates = pd.date_range('1/1/2000', periods=8)
df = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])

我想更新一个日期:2000-01-03。我无法提供我的数据片段,因为它是实时数据。

最佳答案

正如您从警告中看到的那样,您应该使用 loc[row_index, col_index]。当您对数据进行子集化时,您会得到索引值。你只需要传递 row_index 然后用逗号 col_name:

df.loc[df['month'] == 'Feb', 'A'] = df.loc[df['month'] == 'Feb', 'B'] + df.loc[df['month'] == 'Feb', 'C'] + df.loc[df['month'] == 'Feb', 'D'] 

关于python - 使用 loc 更新数据框 python pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34499584/

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