【问题标题】:Python Pandas, Try to update cell valuePython Pandas,尝试更新单元格值
【发布时间】:2021-07-14 10:05:22
【问题描述】:

我有 2 个数据框,都带有日期列:
我需要在第一个数据框中设置在第二个数据框中找到的特定列的值,
所以首先我找到了第一个数据帧的正确行:

id_row = int(dataset.loc[dataset["time"] == str(searchs.index[x])].index[0]) #example: 910

然后我想在这一行更新['search_volume'] 列的值:910
我会这样做:

dataset['search_volume'][id_row] = searchs[kw_list[0]][x]

但我得到了这个错误:

/root/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:8: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

我的完整代码是,但没有工作,没有任何更新。

for x in range(len(searchs)):
    id_row = int(dataset.loc[dataset["time"] == str(searchs.index[x])].index[0])
    dataset['search_volume'][id_row] = searchs[kw_list[0]][x]

如果我手动测试更新,它工作正常:

dataset['search_volume'][910] = searchs[kw_list[0]][47]

什么附加?!

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    使用.loc:

    dataset.loc[910, 'search_volume'] = searchs.loc[47, kw_list[0]]
    

    有关错误消息的更多信息,see this

    此外,还有更有效的方法可以做到这一点。根据经验,如果您在数据帧上循环,您通常会做错事。一些潜在的解决方案:pd.DataFrame.joinpd.merge、掩蔽、pd.DataFrame.where

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 2022-07-11
      • 2022-12-15
      • 2014-05-30
      • 2020-10-01
      • 2014-04-04
      • 1970-01-01
      • 2012-09-24
      相关资源
      最近更新 更多