[英]How to Look-up values in Pandas dataframe
I have a dataframe like this.我有一个这样的数据框。
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
I am trying to add a column called 'LastPrice' which finds the Ticker's last date price.我正在尝试添加一个名为“LastPrice”的列,用于查找股票代码的最后日期价格。 Dates are not consecutive.
日期不连续。 Thanks.
谢谢。
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
Suppose your data is ordered by date, you can use groupby and shift.假设您的数据按日期排序,您可以使用 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
You can lookup values using many methods, here is one of the easier ways.您可以使用多种方法查找值,这是一种更简单的方法。
df["Ticker"]=="AAPL"
will return an array of True/False values. df["Ticker"]=="AAPL"
将返回一个真/假值数组。 True when df["Ticker"]
contains "AAPL"
.df["Ticker"]
包含"AAPL"
。 df.loc
will locate in the dataframe, where the True value in the df["Ticker"]=="AAPL"
array corresponds with the row in the dataframe. df.loc
将定位在数据帧中,其中df["Ticker"]=="AAPL"
数组中的 True 值与数据帧中的行相对应。 Thats why you only see rows where df["Ticker"]=="AAPL"
.df["Ticker"]=="AAPL"
。df # your df
df_AAPL = df.loc[df["Ticker"]=="AAPL"]
df.loc
to locate the price column.df.loc
来定位价格列。df_AAPL_price = df_AAPL.loc[:,"Price"]
lambda
function and apply it across the columns in the dataframe, hence axis = 1
.lambda
函数并将其应用于数据框中的列,因此axis = 1
。 This function takes in values in the rows and returns True
if row["Date"] == "2019-03-27" and row["Ticker"] == "AAPL"
else False
.row["Date"] == "2019-03-27" and row["Ticker"] == "AAPL"
else False
,则此函数接受行中的值并返回True
。 Same concept as in point 1, df.loc
is used to locate where in the dataframe that True
occurs in the array.df.loc
用于定位True
在数组中出现的数据帧中的位置。 You can think of it as dataframe = [1,2,3], array = [True, False, True], and match them up, then only take the value if it is True in the array.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.