准备数据
import pandas as pd
from io import StringIO
data = '''\
Date Velocity Direction
3/12/2011 0:00 1.0964352 10
3/12/2011 0:30 1.1184975 15
3/12/2011 1:00 0.48979592 20
3/12/2011 1:30 0.13188942 45
'''
df = pd.read_csv(StringIO(data), sep=r'\s{2,}', parse_dates=[0], dayfirst=True)
我在这里使用一个技巧。由于Date
列中的日期包含时间元素,它们被单个空白分隔,所以我将列分隔为两个或更多个空格。这就是为什么我给分隔符作为正则表达式sep=r'\s{2,}'
。但是,当然在CSV列中通常用逗号分隔,这使得事情变得更容易(默认设置为sep=','
)。
请注意,Date
列已被解析为日期。其列类型是datetime64
。
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
Date 4 non-null datetime64[ns]
Velocity 4 non-null float64
Direction 4 non-null int64
dtypes: datetime64[ns](1), float64(1), int64(1)
memory usage: 176.0 bytes
通过设置Date
列作为索引绘制数据是简单的:
df.set_index('Date').plot()
这将导致在一个线图,其中两者的速度和方向被绘制为每个时间戳。
您可能会添加导入,只是为了说明问题。 – gregory
@gregory感谢您的提示。我加了他们。 – dotcs
非常感谢。但是,我得到一个错误:df = pd.read_csv(StringIO(data),sep = r'\ s {2,}',parse_dates = [0],dayfirst = True)你知道为什么吗? TypeError:initial_value必须是unicode或None,而不是str – Barack