subaochen / subaochen.github.io

MIT License
1 stars 3 forks source link

pandas学习笔记 #13

Open subaochen opened 5 years ago

subaochen commented 5 years ago

https://subaochen.github.io/python/2019/05/19/pandas-note/

subaochen commented 5 years ago

关于DataFrame的索引需要特别说明一下:索引不是DataFrame数据的一部分,只是为了引用数据方便而加入的。如果将一列通过set_index指定为索引,则这一列无法再通过df['colname']的方式引用,只能通过df['index']引用。

在read_csv或者read_sql_query的时候,可以在参数中指定index_col,自动将某一列变成索引。或者在读入到DataFrame后,通过set_index重新指定索引。

subaochen commented 5 years ago

关于日期的特殊用法:在read_cvs或者read_sql_query的时候,可以将日期类型的字段转换为DataFrame的日期类型,方法是在使用参数parse_dates=True。只有将日期字段转换为DataFrame的日期类型,才能在plot的时候自动显示为日期。

下面是一个简单的示例,注意到下沉的列即为索引(index):

dataset_his = pd.read_sql_query(query, con=engine, \
                index_col=['stat_date'],parse_dates=['stat_date'])
...
plt.plot(dataset_his.index,dataset_his.price)
price
stat_date
2010-10-12 3.00
2010-10-13 3.00
2010-10-19 3.00
2010-10-20 2.65
2010-10-21 2.23