我有一个数据帧df,如下所示:
df = pd.DataFrame({'date': [20121231,20130102, 20130105, 20130106, 20130107, 20130108],'price': [25, 163, 235, 36, 40, 82]})
如何将df['date']
设为date type
并将'price'
设为y-label
和'date'
设为x-label
?
非常感谢。
答案 0 :(得分:3)
将to_datetime
与参数format
一起使用,选中http://strftime.org/
:
df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')
print (df)
date price
0 2012-12-31 25
1 2013-01-02 163
2 2013-01-05 235
3 2013-01-06 36
4 2013-01-07 40
5 2013-01-08 82
然后是plot
:
df.plot(x='date', y='price')
答案 1 :(得分:1)
import pandas as pd
%matplotlib inline
df = pd.DataFrame({'date': [20121231,20130102, 20130105, 20130106, 20130107,
20130108],'price': [25, 163, 235, 36, 40, 82]})
df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')
df.plot(x='date', y='price')
答案 2 :(得分:1)
使用import json
import subprocess
filename = "/home/umesh/Downloads/scripts/cloud-init.log"
def convert_to_json_log(line):
""" convert each line to json format """
log = {}
log['msg'] = line
log['logger-name'] = 'cloud-init'
log['ServiceName'] = 'Contentprocessing'
return json.dumps(log)
def log_as_json(filename):
f = subprocess.Popen(['cat','-F',filename],
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
while True:
line = f.stdout.readline()
log = convert_to_json_log(line)
print log
with open("/home/umesh/Downloads/outputs/cloud-init-json.log", 'a') as new:
new.write(log + '\n')
log_as_json(filename)
,您可以将 date 列直接转换为pandas
类型。然后,您可以使用datetime
进行绘制。看看this answer以及this one。
matplotlib
结果: