簡體   English   中英

pandas 遍歷唯一值的一列並獲取另一列的值

[英]pandas iterate over one column over unique value and get another column's values

我有一個這樣的數據框,我想遍歷產品列並從每個單獨的產品(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]

即每個產品只有兩個日期(從倒數第二行到倒數第三行)。

我實際上對循環很不好,所以有人可以幫忙嗎?

使用df.groupby.nth

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']

或者,沒有循環,使用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))

請嘗試以下操作:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM