Essah Crypto
Essah Crypto

Reputation: 37

How to create headers for csv file in pandas

I want to create a chart for bitcoin price

To create my chart i use this script:

while True:
    url = requests.get("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").json()
    price = url['bitcoin']['usd']
    f = open("chart.csv", "a")
    now = time.time()
    f.write(str(price) + ", " + str(now) + "\n")
    f.close()
    time.sleep(120)

which gives me following output:

47742, 1614355728.759062
47742, 1614355849.1553347
47935, 1614355969.668541
47935, 1614356090.0655239
47922, 1614356210.4580832
47922, 1614356331.5841808
47900, 1614356453.6750243
47900, 1614356574.6440663

And when i try to plot the data with matplotlib i use this script:

plt.plot(price, date)
plt.title('Bitcoin Price Chart')
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()

for my variables price and date i want to use the columns from my csv file, but since i dont have any header how can i do this?

I tried to turn the csv file into a numpy array like this

file = open("chart.csv")
numpy_array = np. loadtxt(file, delimiter=",")
print(numpy_array)

Which prints out a nice array, however if i want to split up the array i still cant do it. I tried print(numpy_array[0]) but this prints out only the first row. How can i get the first column and second column so i can than use those for my price and date variables?

Upvotes: 0

Views: 73

Answers (1)

jusstol
jusstol

Reputation: 126

You can use pandas.read_csv() with arguments :

import pandas as pd

df = pd.read_csv('chart.csv', header=None, names=['price', 'date'])
print(df)

   price          date
0  47742  1.614356e+09
1  47742  1.614356e+09
2  47935  1.614356e+09
3  47935  1.614356e+09
4  47922  1.614356e+09
5  47922  1.614356e+09
6  47900  1.614356e+09
7  47900  1.614357e+09

And then you can convert the "date" column to date and time to get you going on plotting your chart.

df['date'] = pd.to_datetime(df.date, unit='s')
print(df)

   price                       date
0  47742 2021-02-26 16:08:48.759062
1  47742 2021-02-26 16:10:49.155335
2  47935 2021-02-26 16:12:49.668541
3  47935 2021-02-26 16:14:50.065524
4  47922 2021-02-26 16:16:50.458083
5  47922 2021-02-26 16:18:51.584181
6  47900 2021-02-26 16:20:53.675025
7  47900 2021-02-26 16:22:54.644066

Upvotes: 2

Related Questions