Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply function to all df rows using value from row

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading