传递字符串到数据帧i

2024-10-02 22:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个ProductDf,它有同一产品的多个版本。我想过滤产品的最后一次迭代。所以我就这样做了:

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

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

获取productToPick到字符串中的值

^{pr2}$

一旦我在一个系列中得到这个值,我手动调用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'

Tags: 字符串index产品isintegerpointresetgroupby
2条回答

Pandas Dataframeiloc方法只对整型索引值有效。如果要使用字符串值作为从pandas dataframe访问数据的索引,则必须使用pandas dataframeloc方法。在

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

Use of Pandas Dataframe iloc method

Use of Pandas Dataframe loc method

好吧,我想你把它弄糊涂了。在

给定一个如下所示的数据帧:

   avgPrice productId startDtTime  totalSold
0      42.5      A001  01/05/2018        100
1      55.5      A001  02/05/2018        150
2      48.5      A001  03/05/2018        300
3      42.5      A002  01/05/2018        220
4      53.5      A002  02/05/2018        250

我假设您对第2行和第4行(各自productId的最后一个值)感兴趣。在pandas中,最简单的方法是将drop_duplicates()与参数keep='last'一起使用。考虑这个例子:

^{pr2}$

你会得到:

   avgPrice productId startDtTime  totalSold
2      48.5      A001  2018-03-05        300
4      53.5      A002  2018-02-05        250

相关问题 更多 >