当创建具有相同列名的两列的 DataFrame 时,使用 .iat[i,j]
将导致 TypeError。
不过,切换到 .iloc[i,j] 可以解决问题。
在这种情况下,为什么 iat
的行为与 iloc
不同?
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)
x.at[1,'b']
也会出现同样的问题列具有相同的名称。
关于使用 .iat 时出现 Python Pandas TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56905461/