简体   繁体   English

如何在 pandas 中为 csv 文件创建标头

[英]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:这让我关注 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:当我尝试使用 plot 使用 matplotlib 的数据时,我使用此脚本:

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?对于我的变量价格和日期,我想使用 csv 文件中的列,但由于我没有任何 header 我该怎么做?

I tried to turn the csv file into a numpy array like this我试图将 csv 文件变成这样的 numpy 数组

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.我试过print(numpy_array[0])但这只打印出第一行。 How can i get the first column and second column so i can than use those for my price and date variables?我怎样才能得到第一列和第二列,以便我可以将它们用于我的价格和日期变量?

You can use pandas.read_csv() with arguments:您可以将pandas.read_csv()与 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM