gpt4 book ai didi

python - 将字符串传递给数据框 iloc

转载 作者:行者123 更新时间:2023-12-01 01:53:52 26 4
gpt4 key购买 nike

我有一个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:基于位置的索引只能具有[整数、整数切片(包含起始点,排除结束点)、整数列表、 bool 数组]类型

我也尝试过这个:

filteredProductDf = ProductDf[productIndexStr]

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

KeyError: '7,8'

最佳答案

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

通过这些链接了解有关这些方法的更多信息。

Use of Pandas Dataframe iloc method

Use of Pandas Dataframe loc method

关于python - 将字符串传递给数据框 iloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50437427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com