【问题标题】:AttributeError: 'numpy.int64' object has no attribute 'startswith'AttributeError:“numpy.int64”对象没有属性“startswith”
【发布时间】:2015-05-19 19:24:14
【问题描述】:

当我尝试在 ipython 笔记本中使用 seaborn 创建因子图时出现此错误。

这是堆栈跟踪的结尾:

/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.pyc in get_legend_handles_labels(self, legend_handler_map)
   4317             label = handle.get_label()
   4318             #if (label is not None and label != '' and not label.startswith('_')):
-> 4319             if label and not label.startswith('_'):
   4320                 handles.append(handle)
   4321                 labels.append(label)

AttributeError: 'numpy.int64' object has no attribute 'startswith'

这是我的导入:

import numpy as np
import pandas as pd
from pandas import Series,DataFrame

import math

import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline

from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split

from sklearn import metrics

import statsmodels.api as sm

这是我的代码:

df = sm.datasets.fair.load_pandas().data
df['had_affair'] = df.affairs.apply(lambda x: 1 if x != 0 else 0)
sns.factorplot('age', data=df, hue='had_affair', palette='coolwarm')

问题似乎是我用于hue 的列是整数而不是字符串。使用df['had_affair_str'] = df.had_affair.apply(str) 之类的东西创建一个新列,然后使用had_affair_str 作为我的hue 使错误消失,但我正在遵循的在线教程使用这个确切的代码而没有任何错误。这是 matplotlib 或 seaborn 的已知问题吗?我的其中一个包裹过期了吗?

以下是我的 python 包的版本:

ipython==3.1.0
numpy==1.9.2
pandas==0.16.1
matplotlib==1.4.3
seaborn==0.5.1
scikit-learn==0.16.1
statsmodels==0.6.1

编辑:

df.info() 的输出:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 6366 entries, 0 to 6365
Data columns (total 11 columns):
rate_marriage      6366 non-null float64
age                6366 non-null float64
yrs_married        6366 non-null float64
children           6366 non-null float64
religious          6366 non-null float64
educ               6366 non-null float64
occupation         6366 non-null float64
occupation_husb    6366 non-null float64
affairs            6366 non-null float64
had_affair         6366 non-null int64
had_affair_str     6366 non-null object
dtypes: float64(9), int64(1), object(1)
memory usage: 596.8+ KB

【问题讨论】:

  • 你确定 'label' 总是一个字符串吗? .
  • 我正在关注一个在线教程,其中讲师使用相同的代码,但没有错误。除此之外,matplotlib 无法处理使用非字符串列作为标签对我来说毫无意义。如果它需要使用startswith,它似乎应该足够聪明地在某个地方调用str。我已经更新了我的问题,明确表示我相信这段代码应该可以正常运行。
  • 你的代码对我来说运行良好,没有任何 dtype 转换,你能发布df.info()的输出吗
  • 好吧。 “足够聪明”还没有具体的定义。但是我同意应该很好。但软件的整个理念从根本上说是建立在一个商定的方法参数契约之上。 :)
  • @EdChum 编辑了我的帖子以包含df.info()的输出

标签: python matplotlib ipython-notebook seaborn


【解决方案1】:

matplotlib 期望标签系列 had_affair 的 dtypes 是对象/字符串,但它是 numpy.int64

您可以使用以下命令将 numpy.int64 强制转换为字符串:

df['had_affair'] = df['had_affair'].astype(str)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2013-07-29
    • 2017-10-05
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多