【发布时间】:2018-06-23 12:53:15
【问题描述】:
我一直在观看有关使用 Python 进行数据分析的在线课程。当我完全按照导师的做法进行操作时,我遇到了一个问题。基本上,我从 seaborn 中提取了一个名为“flights”的数据框,并设置了索引“year”和“month”并将其拆开。使用以下代码:
import seaborn
import pandas as pd
flights = seaborn.load_dataset("flights")
flights_indexed = flights.set_index(["year","month"])
flights_unstacked = flights_indexed.unstack()
flights_unstacked
the final data frame is like this
然后我尝试使用以下代码在末尾添加一个名为“Total”的新列,用于表示每年的总和:
flights_unstacked["passengers"]["Total"] = flights_unstacked.sum(axis = 1)
但它引发了TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category.
我是使用 pandas 进行数据操作的新手。谁能告诉我如何解决这个问题?这是版本问题吗,因为在线讲师做了完全一样的事情,但他的作品很好。 PS:我使用 Python 2.7 和 pandas 0.20.3。
【问题讨论】:
标签: python pandas dataframe typeerror