python - 将字符串传递给数据框 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'
解决方案
Pandas Dataframe iloc方法仅适用于整数类型索引值。如果您想使用字符串值作为从 pandas 数据帧访问数据的索引,那么您必须使用 Pandas Dataframe loc方法。
从这些链接了解更多关于这些方法的信息。
推荐阅读
- matlab - LabVIEW中的空向量
- c - 在 C 中,块范围的变量存储在哪里?
- kubernetes - 在 pod 运行时挂载 Kubernetes secret
- html - 为什么我的社交媒体图标会离开屏幕?
- unit-testing - 如何使用 Vue Test Utils 在插槽范围内的模板内查找组件
- c# - 从另一个类调用时字典未填充值
- postgresql - Postgresql:我想以如下方式插入数据 -
- python - 如何在冻结的数据类自定义 __init__ 方法中设置属性?
- java - 使用 java-1.8.0-amazon-corretto 时缺少 jdk
- c++ - 使用 for 循环打印字符串数组无法正常工作(C++)