使用 .iat 时出现 Python Pandas TypeError

标签 python python-3.x pandas

当创建具有相同列名的两列的 DataFrame 时,使用 .iat[i,j] 将导致 TypeError。 不过,切换到 .iloc[i,j] 可以解决问题。 在这种情况下,为什么 iat 的行为与 iloc 不同?

python版本:3.6.1 Pandas 版本:0.20.1

import pandas as pd
x = pd.DataFrame([[1,2,3],[4,5,6]],columns=['a','b','a'])
x.iloc[1,1] # works fine
x.iat[1,1]  # TypeError

TypeError: len() of unsized object

最佳答案

似乎当列名不唯一时,您会遇到这个充当索引器的函数:

def _iget_item_cache(self, item):
    """Return the cached item, item represents a positional indexer."""
    ax = self._info_axis
    if ax.is_unique:
        lower = self._get_item_cache(ax[item])
    else:
        lower = self._take(item, axis=self._info_axis_number,
                           convert=True)
    return lower

ax.is_unique为 False 则调用 self._take ,问题是这个函数调用 maybe_convert_indices它需要一个数组,但只得到 int程序崩溃是因为 mask = indices < 0是一个 bool 并且没有 .any()方法

两种解决方案:
好处:
避免相同的命名列,您的程序可以正常运行 x = pd.DataFrame([[1,2,3],[4,5,6]],columns=['a','b','c'])

丑陋: 修改pands源码并更改 lower = self._take(item, axis=self._info_axis_number, convert=True)lower = self._take([item], axis=self._info_axis_number, convert=True)

PS: 如果您使用 x.at[1,'b'] 也会出现同样的问题列具有相同的名称。

关于使用 .iat 时出现 Python Pandas TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56905461/

相关文章:

python - 在很多类 : DRY? 上定义相同的方法覆盖

python - 使用 statsmodels 创建残差图

python - 在python3中将hsl转换为十六进制

python - 使用summary_out时将回归结果导出为csv文件

python - 匹配来自两个不同数据帧的键

python - Python 和 C/C++ 中的可变/不可变对象(immutable对象)

python - Apache Spark 使用的 python 版本

python - 如何在 Python 中获得相同的输出示例?

python - 如何将包含unicode escape\u####的字符串转换为utf-8字符串

python - 获取第二个系列中第一个系列中元素的索引