Pandas在唯一值上迭代一列并获取另一列的值

2024-06-16 12:32:30 发布

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

我有一个这样的数据框架,我想迭代product列,从每个产品(a和B)的日期中获取倒数第二个和倒数第三个值

0. product Date  earning
1. A       202001 123 
2. A       202002 145
3. A       202003 150
4. A       201401 160
5. A       Total  578 
5. B       201901 123 
6. B       201902  145
7. B       201903  150
8. B       201402  160
9. B       Total   578

下面是我正在尝试的示例代码

dates1 = []
dates2 = []


for i in (0,len(test2['product'])):
    s = re.findall('\d+',str(test2.loc[test2.index[-2],'Date']))
    dates1.append(s)
    e = re.findall('\d+',str(test2.loc[test2.index[-3],'Date']))
    dates2.append(e)

所需输出:

date1 = [201401,201402]
date2 = [202003,201903]

即每个产品只有两个日期(从倒数第二行和倒数第三行开始)

事实上我不擅长循环,有人能帮我吗


Tags: 数据redateindex产品productloctotal
3条回答

请尝试以下操作:

date1=[test2[test2['product']==i].iloc[-2]['Date'] for i in test2.product.unique()]
date2=[test2[test2['product']==i].iloc[-3]['Date'] for i in test2.product.unique()]

>>>print(date1) 

[201401,201402]

>>>print(date2

[202003,201903]

或者,在没有循环的情况下,使用pd.DataFrame.groupby

date1 = list(test2.groupby("product")["Date"].apply(lambda x: x.iloc[-2])
date2 = list(test2.groupby("product")["Date"].apply(lambda x: x.iloc[-3])

编辑

或者,正如@yatu所指出的,更好的是,您还可以利用nth

date1 = list(test2.groupby("product")["Date"].nth(-2))
date2 = list(test2.groupby("product")["Date"].nth(-3))

使用^{}

In [683]: date1 = df.groupby('product').Date.nth(-2).tolist()

In [684]: date2 = df.groupby('product').Date.nth(-3).tolist()

In [685]: date1
Out[685]: ['201401', '201402']

In [686]: date2
Out[686]: ['202003', '201903']

相关问题 更多 >