gpt4 book ai didi

python - 我可以找到替代的 `.loc` 替代 Pandas 数据框中的替换功能吗

转载 作者:行者123 更新时间:2023-12-01 09:24:46 25 4
gpt4 key购买 nike

之前,我问How to update series based on other pandas dataframe ,存在 3 个答案,但其中 3 个给出了警告,通常我会忽略这一点,但这是出于生产目的,所以我不能。这是答案和警告:

1

s = df2.set_index('Nation')['Capital City']
df1['Capital'] = df1['Country'].map(s).fillna(df1['Capital'])

警告

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

2

df1['Capital'] = df1['Country'].replace(s)

警告

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

3

s = df2.set_index('Nation')['Capital City']
df1['Capital'].update(df1['Country'].map(s))

警告

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
exec(code_obj, self.user_global_ns, self.user_ns)
/home/ubuntu/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning:
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

如何减少警告

最佳答案

问题显然出在过滤之前的一行中。

解决方案是添加 copy像:

df1 = df[df['col'] == 10].copy()

说明:

如果稍后修改 df1 中的值,您会发现修改不会传播回原始数据 (df),并且 Pandas 发出警告。

关于python - 我可以找到替代的 `.loc` 替代 Pandas 数据框中的替换功能吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50523502/

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