首页 > 解决方案 > 将字符串传递给数据框 iloc

问题描述

我有一个ProductDf相同产品的多个版本。我想过滤产品的最后一次迭代。所以我这样做如下:

productIndexDf= ProductDf.groupby('productId').apply(lambda 
x:x['startDtTime'].reset_index()).reset_index()        

productToPick = productIndexDf.groupby('productId')['index'].max()

将 productToPick 的值转换为字符串

productIndex = productToPick.to_string(header=False, 
index=False).replace('\n',' ')
productIndex  = productIndex.split()

productIndex = list(map(int, productIndex))
productIndex.sort()

productIndexStr = ','.join(str(e) for e in productIndex)

一旦我在一个系列中得到它,我手动调用 loc 函数并且它可以工作:

filteredProductDf = ProductDf.iloc[[7,8],:]

如果我将字符串传递给它,我会收到一个错误:

filteredProductDf = ProductDf.iloc[productIndexStr,:]

ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types

我也试过这个:

filteredProductDf = ProductDf[productIndexStr]

但后来我得到了这个问题:

KeyError: '7,8'

标签: pythonpandaspython-3.5

解决方案


Pandas Dataframe iloc方法仅适用于整数类型索引值。如果您想使用字符串值作为从 pandas 数据帧访问数据的索引,那么您必须使用 Pandas Dataframe loc方法。

从这些链接了解更多关于这些方法的信息。

Pandas Dataframe iloc方法的使用

Pandas Dataframe loc方法的使用


推荐阅读