Python pandas值错误仍然显示,但代码完全正确,并正常加载可视化
我真的想使用Python pandas值错误仍然显示,但代码完全正确,并正常加载可视化,python,python-3.x,pandas,dataframe,jupyter-notebook,Python,Python 3.x,Pandas,Dataframe,Jupyter Notebook,我真的想使用pd.options.mode.chained_assignment=None,但我想要一个没有错误的代码 我的起始代码: 导入日期时间 将牵牛星导入为alt 进口经营者 作为pd进口熊猫 s=pd.read_csv('../../data/aparecida small sample.csv',parse_dates=['date'])) 城市=s[s['city']=='Aparecida'] 根据公司代码: 这段代码工作正常,可以正常加载可视化图像,但它仍然显示pandas错
pd.options.mode.chained_assignment=None
,但我想要一个没有错误的代码
我的起始代码:
导入日期时间
将牵牛星导入为alt
进口经营者
作为pd进口熊猫
s=pd.read_csv('../../data/aparecida small sample.csv',parse_dates=['date']))
城市=s[s['city']=='Aparecida']
根据公司代码:
这段代码工作正常,可以正常加载可视化图像,但它仍然显示pandas错误,要求尝试设置
。loc[row\u indexer,col\u indexer]=value,而不是,然后我阅读了其链接引用的文档“Returning a view vs a copy”,并尝试了这段代码,但仍然显示了相同的错误。这是带有loc
的代码:
#第一次尝试
DentotalCases.loc[“title”]=“已确认”
TENTOTALDETHS.loc[“标题”]=“死亡”
TENTOTALRECOVERED.loc[“title”]=“已恢复”
#第二次尝试
试探性谈话[“标题”]。loc=“已确认”
试探性死亡[“标题”]。loc=“死亡”
TENTOTALRECOVERED[“title”]。loc=“已恢复”
以下是错误消息:
<ipython-input-6-f16b79f95b84>:6: 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
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
tempTotalCases["title"] = "Confirmed"
<ipython-input-6-f16b79f95b84>:9: 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
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
tempTotalDeaths["title"] = "Deaths"
<ipython-input-6-f16b79f95b84>:12: 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
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
tempTotalRecovered["title"] = "Recovered"
更新2
我遵循了答案,它奏效了,但还有另一个问题:
temp = tempTotalCases.append(tempTotalDeaths)
temp = temp.append(tempTotalRecovered)
错误日志:
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
iloc._setitem_with_indexer(indexer, value, self.name)
InvalidIndexError: Reindexing only valid with uniquely valued Index objects
---------------------------------------------------------------------------
InvalidIndexError Traceback (most recent call last)
<ipython-input-7-b2649a676837> in <module>
17 tempTotalRecovered.loc["title"] = _("Recovered")
18
---> 19 temp = tempTotalCases.append(tempTotalDeaths)
20 temp = temp.append(tempTotalRecovered)
21
~/GitLab/Gustavo/global/.env/lib/python3.9/site-packages/pandas/core/frame.py in append(self, other, ignore_index, verify_integrity, sort)
7980 to_concat = [self, other]
7981 return (
-> 7982 concat(
7983 to_concat,
7984 ignore_index=ignore_index,
~/GitLab/Gustavo/global/.env/lib/python3.9/site-packages/pandas/core/reshape/concat.py in concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy)
296 )
297
--> 298 return op.get_result()
299
300
~/GitLab/Gustavo/global/.env/lib/python3.9/site-packages/pandas/core/reshape/concat.py in get_result(self)
514 obj_labels = obj.axes[1 - ax]
515 if not new_labels.equals(obj_labels):
--> 516 indexers[ax] = obj_labels.get_indexer(new_labels)
517
518 mgrs_indexers.append((obj._mgr, indexers))
~/GitLab/Gustavo/global/.env/lib/python3.9/site-packages/pandas/core/indexes/base.py in get_indexer(self, target, method, limit, tolerance)
3169
3170 if not self.is_unique:
-> 3171 raise InvalidIndexError(
3172 "Reindexing only valid with uniquely valued Index objects"
3173 )
InvalidIndexError: Reindexing only valid with uniquely valued Index objects
试图在数据帧切片的副本上设置值
请参阅文档中的注意事项:https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view vs-a-copy
iloc.\u setitem\u和索引器(索引器、值、self.name)
InvalidIndexError:重新索引仅对唯一值的索引对象有效
---------------------------------------------------------------------------
InvalidIndexError回溯(最近一次调用上次)
在里面
17 TENTOTALRECOVERED.loc[“标题”]=“已恢复”)
18
--->19 temp=TENTOTALCASES.append(TENTOTALDETHS)
20温度=温度附加(试运行恢复)
21
附加中的~/GitLab/Gustavo/global/.env/lib/python3.9/site-packages/pandas/core/frame.py(self、other、忽略索引、验证完整性、排序)
7980 to_concat=[自身,其他]
7981返回(
->7982康卡特(
7983至_concat,
7984忽略索引=忽略索引,
concat中的~/GitLab/Gustavo/global/.env/lib/python3.9/site-packages/pandas/core/restrape/concat.py(对象、轴、连接、忽略索引、键、级别、名称、验证完整性、排序、复制)
296 )
297
-->298返回操作获取结果()
299
300
获取结果(self)中的~/GitLab/Gustavo/global/.env/lib/python3.9/site-packages/pandas/core/restrape/concat.py
514 obj_标签=obj.轴[1-轴]
515如果不是新标签,则等于(obj标签):
-->516索引器[ax]=对象标签。获取索引器(新标签)
517
518经理索引器追加((对象经理索引器))
get_indexer中的~/GitLab/Gustavo/global/.env/lib/python3.9/site-packages/pandas/core/index/base.py(self、target、method、limit、tolerance)
3169
3170如果不是self.is_唯一:
->3171 raise INVALIDIDEX错误(
3172“仅对唯一值索引对象重新编制索引有效”
3173 )
InvalidIndexError:重新索引仅对唯一值的索引对象有效
这个设置的copywarning
是一个警告,而不是一个错误
。这个区别的重要性在于pandas
不确定你的代码是否会产生预期的输出,所以让程序员做出这个决定,错误
意味着某些东西肯定是错误的ng
设置WithCopyWarning
警告您,当您执行类似于df['First selection']['Second selection']
的操作时,与df.loc[:,('First selection',Second selection')相比,两者之间存在差异
在第一种情况下,发生两个单独的事件df['first selection']
,然后从该事件返回的对象将用于返回的下一个选择df['Second selection']
pandas
无法知道返回的df
是原始的df
还是此对象的临时“视图”。大多数情况下都无关紧要(有关更多信息,请参阅文档)…但是,如果您想更改对象临时视图上的值,您将弄不清楚为什么代码运行时没有错误,但您看不到所做的更改。使用.loc
将'First selection'
和'Second selection'
捆绑到一个调用中,这样熊猫
就可以保证返回的内容没有错误只是一个风景
you linked show向您解释了为什么您尝试使用.loc
无法达到预期效果(例如,取自文档):
您的代码中有一些类似的内容。请看一下testotalcases
是如何创建的:
city = s[s['city'] == 'Aparecida']
# some lines of code
tempTotalCases = city[['date','total_cases']]
然后在尝试执行此操作之前再执行几行代码:
tempTotalCases.loc["title"] = "Confirmed"
因此,pandas
抛出警告
与原始问题分开,您可能会发现df.rename()
很有用
您将能够执行以下操作:
city = city.rename(columns={'totalCases': 'total_cases',
'totalDeaths': 'total_deaths',
'totalRecovered': 'total_recovered})
这些都是警告,而不是错误,这就是为什么它会显示SettingWithCopyWarning
以及为什么它似乎成功地执行了某些操作。您仍然应该尝试以避免警告的方式编写代码。开始时,请尝试采纳警告中明确给出的建议。“然后我正在阅读文档”返回视图而不是副本“其链接引用并尝试了此代码”尝试了什么代码?警告告诉Try using.loc[row\u indexer,col\u indexer]=改为value
。我在你的帖子中根本没有看到任何提到.loc
的代码。我们只能在我们实际看到的代码上帮助你。完成,@KarlKnechtel。非常感谢,我理解你的答案并应用了逻辑,几乎成功了,但出现了另一个错误。这是关于
city = s[s['city'] == 'Aparecida']
# some lines of code
tempTotalCases = city[['date','total_cases']]
tempTotalCases.loc["title"] = "Confirmed"
city = city.rename(columns={'totalCases': 'total_cases',
'totalDeaths': 'total_deaths',
'totalRecovered': 'total_recovered})