【问题标题】:pandas >= 0.18 - setting multi-index name on df from read_csv resulting in TypeErrorpandas >= 0.18 - 从 read_csv 在 df 上设置多索引名称导致 TypeError
【发布时间】:2016-08-20 13:35:07
【问题描述】:

我遇到了一个仅在将 pandas 更新到 >= 0.18 后才开始发生的错误

我有一段代码可以打开多个 csv 文件并将它们连接到一个多索引数据帧中。作为 pd.concat 步骤的一部分,我使用names=['Sweep', 'Index'] 设置索引名称。在从 0.17 更新到 0.18 之前,这工作正常,但自从更新后,我得到了下面显示的回溯。

我已将问题减少到能够通过此重现(示例 csv 可以在 here 找到):

filename = './example.csv'
df = pd.read_csv(filename)
pd.concat([df, ], keys=['Sweep1', ], names=['Sweep', 'Index'])

这会导致以下回溯:

Traceback (most recent call last):
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\indexes\range.py", line 124, in _simple_new
    return RangeIndex(start, stop, step, name=name, **kwargs)
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\indexes\range.py", line 73, in __new__
    start = _ensure_int(start, 'start')
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\indexes\range.py", line 59, in _ensure_int
    new_value = int(value)
TypeError: only length-1 arrays can be converted to Python scalars

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\core\base.py", line 63, in __repr__
    return str(self)
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\core\base.py", line 42, in __str__
    return self.__unicode__()
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\core\frame.py", line 534, in __unicode__
    line_width=width, show_dimensions=show_dimensions)
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\core\frame.py", line 1486, in to_string
    show_dimensions=show_dimensions)
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\core\format.py", line 378, in __init__
    self._chk_truncate()
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\core\format.py", line 450, in _chk_truncate
    frame.iloc[-row_num:, :]))
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\tools\merge.py", line 834, in concat
    copy=copy)
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\tools\merge.py", line 972, in __init__
    self.new_axes = self._get_new_axes()
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\tools\merge.py", line 1059, in _get_new_axes
    new_axes[self.axis] = self._get_concat_axis()
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\tools\merge.py", line 1111, in _get_concat_axis
    concat_axis = _concat_indexes(indexes)
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\tools\merge.py", line 1129, in _concat_indexes
    return indexes[0].append(indexes[1:])
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\indexes\multi.py", line 1029, in append
    label = self.get_level_values(i)
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\indexes\multi.py", line 666, in get_level_values
    tz=getattr(unique, 'tz', None))
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\indexes\range.py", line 126, in _simple_new
    return Index(start, stop, step, name=name, **kwargs)
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\indexes\base.py", line 214, in __new__
    return Int64Index(data, copy=copy, dtype=dtype, name=name)
  File "C:\Users\User\Anaconda3\lib\site-packages\pandas\indexes\numeric.py", line 107, in __new__
    not issubclass(np.dtype(dtype).type, np.integer)):
TypeError: data type "Index" not understood

我已经在几台不同的机器上尝试过这个(认为可能是 anaconda 的问题),但我到处都遇到了这个问题。

如果我只是生成一个虚拟数据框并执行相同的操作,则不会发生这种情况。即:

df = pd.DataFrame({"Vals1": range(8), "Vals2": range(8)})
pd.concat([df, ], keys=['Sweep1', ], names=['Sweep', 'Index'])

工作正常。

我可以毫无问题地从导入的 csv 设置数据帧的索引名称。即:

filename = './example.csv'
df = pd.read_csv(filename)
df.index.names = ['Index']

工作正常。

奇怪的是,如果我只是在没有 names 参数的情况下运行 concat 步骤,然后在单独的行中设置名称,这会很好。但是,一旦我使用该数据框,就会得到上面显示的回溯。即:

filename = './example.csv'
df = pd.read_csv(filename)
new_df = pd.concat([df, ], keys=['Sweep1', ])
new_df.index.names = ['Sweep', 'Index']

将运行,直到我去查看 new_df。更奇怪的是,我可以做new_df.head() 之类的事情,而且运行良好。但是,如果我只是在终端中输入new_df 并打印出来,我就会得到上面的回溯。

我不知道这里发生了什么,因此我们将不胜感激。

** 编辑 1**

这些是上面链接中提供的文件的前 5 行。

data_dict = {' LED': {0: -0.00030517578125,
  1: 0.0,
  2: -0.00030517578125,
  3: -0.00030517578125,
  4: -0.00030517578125,
  5: 0.0},
 ' Primary': {0: -2.74688720703125,
  1: -2.74566650390625,
  2: -2.74627685546875,
  3: -2.74810791015625,
  4: -2.74749755859375,
  5: -2.745361328125},
 ' Secondary': {0: -0.00152587890625,
  1: -0.00457763671875,
  2: -0.0048828125,
  3: -0.00335693359375,
  4: -0.0048828125,
  5: -0.00518798828125},
 'Time(ms)': {0: 0.0,
  1: 0.10000000000000001,
  2: 0.20000000000000001,
  3: 0.29999999999999999,
  4: 0.40000000000000002,
  5: 0.5}}

df = pd.DataFrame(data_dict)
df.to_csv('temp.csv', index=False)
df = pd.read_csv('temp.csv')
pd.concat([df, ], keys=['Sweep1', ], names=['Sweep', 'Index'])

但是,这不会产生错误。

【问题讨论】:

  • 什么是example.csv?
  • 这是我的数据采集软件生成的csv文件。基本上它是四列数字数据,第一行是列标题。我提供了一个可用于重现此问题的文件的链接(尽管该问题在不同的文件中普遍存在)
  • 对,但没有该数据的代表性示例,我们应该如何帮助您?
  • 我不明白 - 我提供了一个可以使用的文件。
  • 在您的代码中嵌入一小部分数据以生成数据帧。大多数人不太热衷于从互联网上的匿名人士那里下载随机文件

标签: python csv pandas multi-index


【解决方案1】:

这是一个非常有趣的问题。我确定这指向一个错误。

证据

无需下载您的数据,只需使用您的简单示例即可:

df = pd.DataFrame({"Vals1": range(8), "Vals2": range(8)})
pd.concat([df, ], keys=['Sweep1', ], names=['Sweep', 'Index'])

产生你想要的东西。但是,如果您将 range(8) 更改为 range(61)。它以类似的方式爆炸。是的!,61 这个号码似乎有什么特别之处。更重要的是,如果您改为这样做:

df = pd.DataFrame({"Vals1": range(61), "Vals2": range(61)})
df1 = pd.concat([df, ], keys=['Sweep1', ], names=['Sweep', 'Index'])

这很好......直到你尝试print df1。尝试显示数据框时出现错误。

解决方法。

我无法在 MultiIndex.names 属性的第二个位置获得名称,也无法打印/显示它。

df = pd.DataFrame({"Vals1": range(61), "Vals2": range(61)})
df1= pd.concat([df, ], keys=['Sweep1', ], names=['Sweep', ])

演示

为了证明它适用于您的数据

filename = './example.csv'
df = pd.read_csv(filename)
pd.concat([df, ], keys=['Sweep1', ], names=['Sweep', ])

              Time(ms)   Primary   Secondary       LED
Sweep                                                 
Sweep1 0           0.0 -2.746887   -0.001526 -0.000305
       1           0.1 -2.745667   -0.004578  0.000000
       2           0.2 -2.746277   -0.004883 -0.000305
       3           0.3 -2.748108   -0.003357 -0.000305
       4           0.4 -2.747498   -0.004883 -0.000305
       5           0.5 -2.745361   -0.005188  0.000000
       6           0.6 -2.749634   -0.004578  0.000305
       7           0.7 -2.748413   -0.002441 -0.000305
       8           0.8 -2.746277   -0.004883 -0.000305
       9           0.9 -2.743530   -0.005188  0.000305
       10          1.0 -2.743835   -0.006104  0.000610
       11          1.1 -2.747192   -0.003052 -0.000610
       12          1.2 -2.746277   -0.003052 -0.000305
       13          1.3 -2.742310   -0.009460  0.000000
       14          1.4 -2.747192   -0.007324  0.000305
       15          1.5 -2.746887   -0.004272  0.000305
       16          1.6 -2.740479   -0.001526 -0.000305
       17          1.7 -2.745972   -0.004883 -0.000305
       18          1.8 -2.743530   -0.007629  0.000305
       19          1.9 -2.742310   -0.005188  0.000000
       20          2.0 -2.739258   -0.001526  0.000305
       21          2.1 -2.743835   -0.000610  0.000000
       22          2.2 -2.745056   -0.004883 -0.000305
       23          2.3 -2.742615   -0.006714 -0.000305
       24          2.4 -2.739868   -0.004272  0.000610
       25          2.5 -2.738342   -0.006104  0.000000
       26          2.6 -2.740784   -0.003662 -0.000916
       27          2.7 -2.738647   -0.000610  0.000305
       28          2.8 -2.737732    0.000610  0.000000
       29          2.9 -2.739563   -0.004578  0.000000
...                ...       ...         ...       ...
       99970    9997.0 -2.576599   -0.000305 -0.000610
       99971    9997.1 -2.577515   -0.004578 -0.000305
       99972    9997.2 -2.577209   -0.003967  0.000000
       99973    9997.3 -2.578430   -0.003052  0.000000
       99974    9997.4 -2.580566   -0.004272  0.000305
       99975    9997.5 -2.575684   -0.003357 -0.000305
       99976    9997.6 -2.574463   -0.000916 -0.000305
       99977    9997.7 -2.579651   -0.002747  0.000000
       99978    9997.8 -2.576294   -0.010376 -0.000305
       99979    9997.9 -2.578125   -0.005798 -0.000916
       99980    9998.0 -2.576294   -0.001831  0.000000
       99981    9998.1 -2.577820    0.000000  0.000916
       99982    9998.2 -2.581482   -0.007019  0.000000
       99983    9998.3 -2.575073   -0.005493  0.000000
       99984    9998.4 -2.578125   -0.002136 -0.000305
       99985    9998.5 -2.577515    0.003967 -0.000305
       99986    9998.6 -2.575378   -0.005188  0.000000
       99987    9998.7 -2.577515   -0.007935  0.000610
       99988    9998.8 -2.578430   -0.003967 -0.000305
       99989    9998.9 -2.579346   -0.001221  0.000000
       99990    9999.0 -2.577209    0.001221  0.000000
       99991    9999.1 -2.578125   -0.005798  0.000000
       99992    9999.2 -2.577515   -0.005493  0.000000
       99993    9999.3 -2.573853   -0.002747 -0.000305
       99994    9999.4 -2.575378    0.002441 -0.000305
       99995    9999.5 -2.577820   -0.000305  0.000305
       99996    9999.6 -2.575989   -0.006104  0.000000
       99997    9999.7 -2.576294   -0.007019  0.000305
       99998    9999.8 -2.576599   -0.003662  0.000305
       99999    9999.9 -2.573853   -0.000916 -0.000305

[100000 rows x 4 columns]

终于

如果你真的需要那个 'Index' 名字,你可以留下它,只是不要试图显示它。

也很重要

Paul H 是正确的,因为人们并不热衷于从 Internet 下载随机文件。我冒险了。但是,此错误仅在样本数据超过 61 条记录/行时才会出现。

【讨论】:

  • 是的,我发现我可以重命名0级索引,但不能重命名1级索引并且仍然能够显示它。我认为这是一个熊猫错误,应该在他们的问题跟踪器上打开?
猜你喜欢
  • 1970-01-01
  • 2018-09-05
  • 2016-10-24
  • 1970-01-01
  • 2020-10-31
  • 2022-11-29
  • 1970-01-01
  • 1970-01-01
  • 2012-09-11
相关资源
最近更新 更多