【问题标题】:The pandas value error still shows, but the code is totally correct and it loads normally the visualization熊猫值错误仍然显示,但代码完全正确,并且可以正常加载可视化
【发布时间】:2021-04-14 22:27:17
【问题描述】:

我真的很想使用pd.options.mode.chained_assignment = None,但我想要一个没有错误的代码。

我的起始码:

import datetime
import altair as alt
import operator
import pandas as pd
s = pd.read_csv('../../data/aparecida-small-sample.csv', parse_dates=['date'])

city = s[s['city'] == 'Aparecida']

基于@dpkandy的代码:

city['total_cases'] = city['totalCases']
city['total_deaths'] = city['totalDeaths']
city['total_recovered'] = city['totalRecovered']

tempTotalCases = city[['date','total_cases']]
tempTotalCases["title"] = "Confirmed"

tempTotalDeaths = city[['date','total_deaths']]
tempTotalDeaths["title"] = "Deaths"

tempTotalRecovered = city[['date','total_recovered']]
tempTotalRecovered["title"] = "Recovered"

temp = tempTotalCases.append(tempTotalDeaths)
temp = temp.append(tempTotalRecovered)

totalCases = alt.Chart(temp).mark_bar().encode(alt.X('date:T', title = None), alt.Y('total_cases:Q', title = None))
totalDeaths = alt.Chart(temp).mark_bar().encode(alt.X('date:T', title = None), alt.Y('total_deaths:Q', title = None))
totalRecovered = alt.Chart(temp).mark_bar().encode(alt.X('date:T', title = None), alt.Y('total_recovered:Q', title = None))

(totalCases + totalRecovered + totalDeaths).encode(color=alt.Color('title', scale = alt.Scale(range = ['#106466','#DC143C','#87C232']), legend = alt.Legend(title="Legend colour"))).properties(title = "Cumulative number of confirmed cases, deaths and recovered", width = 800)

此代码运行良好并正常加载可视化图像,但仍然显示 pandas 错误,要求尝试设置 .loc[row_indexer,col_indexer] = value instead,然后我正在阅读文档“返回视图与副本”,其链接引用和试过这段代码,但它仍然显示相同的错误。这是loc的代码:

# 1st attempt
tempTotalCases.loc["title"] = "Confirmed"
tempTotalDeaths.loc["title"] = "Deaths"
tempTotalRecovered.loc["title"] = "Recovered"

# 2nd attempt
tempTotalCases["title"].loc = "Confirmed"
tempTotalDeaths["title"].loc = "Deaths"
tempTotalRecovered["title"].loc = "Recovered"

这是错误信息:

<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"

Jupyter 和 Pandas 版本:

$ jupyter --version
jupyter core     : 4.7.1
jupyter-notebook : 6.3.0
qtconsole        : 5.0.3
ipython          : 7.22.0
ipykernel        : 5.5.3
jupyter client   : 6.1.12
jupyter lab      : 3.1.0a3
nbconvert        : 6.0.7
ipywidgets       : 7.6.3
nbformat         : 5.1.3
traitlets        : 5.0.5

$ pip show pandas
Name: pandas
Version: 1.2.4
Summary: Powerful data structures for data analysis, time series, and statistics
Home-page: https://pandas.pydata.org
Author: None
Author-email: None
License: BSD
Location: /home/gus/PUC/.env/lib/python3.9/site-packages
Requires: pytz, python-dateutil, numpy
Required-by: ipychart, altair

更新 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

【问题讨论】:

  • 这些是警告,而不是错误,这就是为什么它说 SettingWithCopyWarning 以及为什么它似乎成功地做某事的原因。您仍然应该尝试以避免警告的方式编写代码。首先,请尝试采纳警告中明确提供给您的建议。
  • "然后我正在阅读文档"返回视图与副本",其链接引用并尝试了此代码"尝试过 what 代码?警告说是Try using .loc[row_indexer,col_indexer] = value instead。我在您的帖子中没有看到任何提到.loc 的代码。我们只能为您提供实际可以看到的代码。
  • 完成,@KarlKnechtel。

标签: python python-3.x pandas dataframe jupyter-notebook


【解决方案1】:

这个SettingWithCopyWarningwarning 而不是error。这种区别的重要性在于 pandas 不确定您的代码是否会产生预期的输出,因此让程序员做出决定,因为 error 意味着肯定有问题。

SettingWithCopyWarning 警告您执行df['First selection']['Second selection']df.loc[:, ('First selection', 'Second selection') 之类的操作之间的区别。

在第一种情况下,发生了两个单独的事件df['First selection'],然后从此返回的对象用于下一个选择returned_df['Second selection']pandas 无法知道 returned_df 是原始的 df 还是该对象的临时“视图”。大部分时间都没有关系(有关更多信息,请参阅文档)...但是如果您想更改对象的临时视图上的值,您会很困惑为什么您的代码运行时没有错误但您没有看不到您所做的更改。使用.loc'First selection''Second selection' 捆绑到一个调用中,因此pandas 可以保证返回的不仅仅是一个视图。

您链接的 documentation 向您展示了为什么您尝试使用 .loc 没有按您的预期工作(例如,取自文档):

def do_something(df):
    foo = df[['bar', 'baz']]  # Is foo a view? A copy? Nobody knows!
    # ... many lines here ...
    # We don't know whether this will modify df or not!
    foo['quux'] = value
    return foo

您的代码中有类似的内容。看看tempTotalCases是如何创建的:

city = s[s['city'] == 'Aparecida']
# some lines of code    
tempTotalCases = city[['date','total_cases']]

然后在你尝试之前再写几行代码:

tempTotalCases.loc["title"] = "Confirmed"

所以pandas 抛出警告。

与您最初的问题分开,您可能会发现df.rename() 很有用。 Link to docs.

您将能够执行以下操作:

city = city.rename(columns={'totalCases': 'total_cases',
                            'totalDeaths': 'total_deaths',
                            'totalRecovered': 'total_recovered})

【讨论】:

  • 非常感谢,我理解了你的回答并应用了逻辑,它几乎成功了,但又出现了一个错误。大约是temp = tempTotalCases.append(tempTotalDeaths)。请检查我的第二次更新。谢谢。
  • 很高兴您取得了进展。如果不知道tempTotalCasestempTotalDeaths 是什么,就很难帮助您解决新错误。该错误表明tempTotalCases.index 不包含唯一值,因此任何按索引对齐或排序的操作都将失败。在尝试 .append() 之前,您可以在您的对象上使用 .reset_index() (注意默认情况下这是不存在的)。或者传递关键字参数 `.append(ignore_index=True) 。您需要查看您的数据以确定最合适的数据。
猜你喜欢
  • 2014-04-20
  • 2014-08-03
  • 2021-09-04
  • 2017-07-18
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多