[英]How to Look-up values in Pandas dataframe
我有一個這樣的數據框。
Date Ticker Price
2019-03-21 AAPL 100
2019-03-21 GOOG 101
2019-03-21 IBM 102
2019-03-25 AAPL 90
2019-03-25 GOOG 91
2019-03-25 IBM 92
2019-03-27 AAPL 110
2019-03-27 GOOG 111
2019-03-27 IBM 112
我正在嘗試添加一個名為“LastPrice”的列,用於查找股票代碼的最后日期價格。 日期不連續。 謝謝。
Date Ticker Price LastPrice
2019-03-21 AAPL 100
2019-03-21 GOOG 101
2019-03-21 IBM 102
2019-03-25 AAPL 90 100
2019-03-25 GOOG 91 101
2019-03-25 IBM 92 102
2019-03-27 AAPL 110 90
2019-03-27 GOOG 111 91
2019-03-27 IBM 112 92
假設您的數據按日期排序,您可以使用 groupby 和 shift。
df['LastPrice'] = (
df.groupby('Ticker')
.apply(lambda x: x.Price.shift())
.reset_index(0, drop=True)
)
Date Ticker Price LastPrice
0 2019-03-21 AAPL 100 NaN
1 2019-03-21 GOOG 101 NaN
2 2019-03-21 IBM 102 NaN
3 2019-03-25 AAPL 90 100.0
4 2019-03-25 GOOG 91 101.0
5 2019-03-25 IBM 92 102.0
6 2019-03-27 AAPL 110 90.0
7 2019-03-27 GOOG 111 91.0
8 2019-03-27 IBM 112 92.0
您可以使用多種方法查找值,這是一種更簡單的方法。
df["Ticker"]=="AAPL"
將返回一個真/假值數組。 當df["Ticker"]
包含"AAPL"
。 df.loc
將定位在數據幀中,其中df["Ticker"]=="AAPL"
數組中的 True 值與數據幀中的行相對應。 這就是為什么你只看到df["Ticker"]=="AAPL"
。df # your df
df_AAPL = df.loc[df["Ticker"]=="AAPL"]
df.loc
來定位價格列。df_AAPL_price = df_AAPL.loc[:,"Price"]
lambda
函數並將其應用於數據框中的列,因此axis = 1
。 如果row["Date"] == "2019-03-27" and row["Ticker"] == "AAPL"
else False
,則此函數接受行中的值並返回True
。 與第 1 點相同的概念, df.loc
用於定位True
在數組中出現的數據幀中的位置。 你可以把它想象成dataframe = [1,2,3], array = [True, False, True],然后將它們匹配起來,然后只取數組中如果為True的值。 所以,在這種情況下,它只會是“1”和“3”。df_new = df.loc[df.apply(lambda row:True if row["Date"] == "2019-03-27" and row["Ticker"] == "AAPL" else False ,axis=1)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.