I have a dataframe column consisting of timestamps which I need to pass to a function as an argument to retrieve a price for that given timestamp. Then create a new "price" column in the dataframe.
The df looks like this:
date_time timestamp
0 2022-09-20 23:55:02 1663718102
1 2022-09-21 23:55:02 1663804502
2 2022-09-22 23:59:02 1663891142
3 2022-09-23 23:59:02 1663977542
4 2022-09-24 23:59:02 1664063942
5 2022-09-25 23:59:03 1664150343
6 2022-09-26 23:59:02 1664236742
7 2022-09-27 23:59:03 1664323143
8 2022-09-28 23:59:03 1664409543
9 2022-09-29 23:59:03 1664495943
10 2022-09-30 23:59:02 1664582342
11 2022-10-01 23:59:02 1664668742
12 2022-10-02 23:59:02 1664755142
13 2022-10-03 23:59:03 1664841543
Currently I can pass any one of these timestamps to the function individually but am unsure how to combine the function and the dataframe to produce the third column.
def fetch_price(timestamp):
data = session_auth.query_kline(
symbol="BTCUSDT",
interval=1,
limit=2,
from_time=timestamp)
price = data["result"][0]["close"]
return price
CodePudding user response:
You can do
df["new_column"] = df.timestamp.apply(fetch_price)
This applies the function to every row/timestamp of your DataFrame and creates a new column "new_column"