如何将 CSV 直接解析为所需的 DataFrame:
将函数字典传递给pandas.read_csv
's converters
关键字参数:
import pandas as pd
import datetime as DT
nfp = pd.read_csv("NFP.csv",
sep=r'[\s,]', # 1
header=None, skiprows=1,
converters={ # 2
0: lambda x: DT.datetime.strptime(x, '%Y%m%d'),
1: lambda x: DT.time(*map(int, x.split(':')))},
names=['Date', 'Time', 'Actual', 'Consensus', 'Previous'])
print(nfp)
yields
Date Time Actual Consensus Previous
0 2014-01-10 13:30:00 74000 196000 241000
1 2013-12-06 13:30:00 241000 180000 200000
2 2013-11-08 13:30:00 200000 125000 163000
3 2013-10-22 12:30:00 163000 180000 193000
4 2013-09-06 12:30:00 193000 180000 104000
5 2013-08-02 12:30:00 104000 184000 188000
6 2013-07-05 12:30:00 188000 165000 176000
7 2013-06-07 12:30:00 176000 170000 165000
8 2013-05-03 12:30:00 165000 145000 138000
9 2013-04-05 12:30:00 138000 200000 268000
-
sep=r'[\s,]'
tells read_csv
分割 csv 的行
正则表达式模式r'[\s,]'
-- 空格或逗号。
- The
converters
参数告诉read_csv
应用给定的
某些列的函数。键(例如 0 和 1)指的是
列索引,值是要应用的函数。
如何在执行 csv 读取后拆分 DataFrame
import pandas as pd
nfp = pd.read_csv("NFP.csv", parse_dates=[0], infer_datetime_format=True)
temp = pd.DatetimeIndex(nfp['DateTime'])
nfp['Date'] = temp.date
nfp['Time'] = temp.time
del nfp['DateTime']
print(nfp)
哪个更快?
这取决于 CSV 的大小。 (感谢杰夫指出了这一点。)
对于小型 CSV,直接将 CSV 解析为所需的形式比解析后使用 DatetimeIndex 更快parse_dates=[0]
:
def using_converter():
nfp = pd.read_csv("NFP.csv", sep=r'[\s,]', header=None, skiprows=1,
converters={
0: lambda x: DT.datetime.strptime(x, '%Y%m%d'),
1: lambda x: DT.time(*map(int, x.split(':')))},
names=['Date', 'Time', 'Actual', 'Consensus', 'Previous'])
return nfp
def using_index():
nfp = pd.read_csv("NFP.csv", parse_dates=[0], infer_datetime_format=True)
temp = pd.DatetimeIndex(nfp['DateTime'])
nfp['Date'] = temp.date
nfp['Time'] = temp.time
del nfp['DateTime']
return nfp
In [114]: %timeit using_index()
100 loops, best of 3: 1.71 ms per loop
In [115]: %timeit using_converter()
1000 loops, best of 3: 914 µs per loop
但是,对于只有几百行或更多行的 CSV,使用 DatetimeIndex 速度更快。
N = 20
filename = '/tmp/data'
content = '''\
DateTime,Actual,Consensus,Previous
20140110 13:30:00,74000,196000,241000
20131206 13:30:00,241000,180000,200000
20131108 13:30:00,200000,125000,163000
20131022 12:30:00,163000,180000,193000
20130906 12:30:00,193000,180000,104000
20130802 12:30:00,104000,184000,188000
20130705 12:30:00,188000,165000,176000
20130607 12:30:00,176000,170000,165000
20130503 12:30:00,165000,145000,138000
20130405 12:30:00,138000,200000,268000'''
def setup(n):
header, remainder = content.split('\n', 1)
with open(filename, 'w') as f:
f.write('\n'.join([header]+[remainder]*n))
In [304]: setup(50)
In [305]: %timeit using_converter()
100 loops, best of 3: 9.78 ms per loop
In [306]: %timeit using_index()
100 loops, best of 3: 9.3 ms per loop
我在哪里可以查到此类信息?
- 有时您可以在以下位置找到示例熊猫食谱 http://pandas.pydata.org/pandas-docs/stable/cookbook.html.
- 有时网络搜索或搜索 Stackoverflow 就足够了。
- 周末下雪了,除了看书什么也不做熊猫文档 http://pandas.pydata.org/pandas-docs/stable/index.html肯定也会有所帮助。
- Install IPython http://ipython.org/。它具有制表符补全功能,如果您键入
?
之后
函数,它为您提供函数的文档字符串。这两个特点
确实可以帮助您快速内省 Python 对象。它还告诉您该函数是在哪个文件中定义的(如果是在纯 Python 中定义的)——这让我……
- 阅读源代码 https://github.com/pydata/pandas
坚持下去。你知道的越多就越容易。
如果您尽了最大努力仍然找不到答案,请在 Stackoverflow 上发布问题。希望您能很快得到答案,并帮助其他人寻找同样的东西。