我有一个CSV文件格式如下:
somefeature,anotherfeature,f3,f4,f5,f6,f7,lastfeature
0,0,0,1,1,2,4,5
Run Code Online (Sandbox Code Playgroud)
我尝试将其视为熊猫系列(使用Python 2.7的pandas每日快照).我尝试了以下方法:
import pandas as pd
types = pd.Series.from_csv('csvfile.txt', index_col=False, header=0)
Run Code Online (Sandbox Code Playgroud)
和:
types = pd.read_csv('csvfile.txt', index_col=False, header=0, squeeze=True)
Run Code Online (Sandbox Code Playgroud)
但两者都不起作用:第一个产生随机结果,第二个只是导入DataFrame而不会挤压.
看起来像pandas只能识别为系列格式如下的CSV格式:
f1, value
f2, value2
f3, value3
Run Code Online (Sandbox Code Playgroud)
但是当功能键位于第一行而不是列时,pandas不想挤压它.
我还能尝试别的吗?这种行为是有意的吗?
gab*_*ous 15
这是我发现的方式:
df = pandas.read_csv('csvfile.txt', index_col=False, header=0);
serie = df.ix[0,:]
Run Code Online (Sandbox Code Playgroud)
对我来说似乎有点愚蠢,因为Squeeze应该已经这样做了.这是一个错误还是我错过了什么?
/编辑:最佳方式:
df = pandas.read_csv('csvfile.txt', index_col=False, header=0);
serie = df.transpose()[0] # here we convert the DataFrame into a Serie
Run Code Online (Sandbox Code Playgroud)
这是将面向行的CSV行转换为pandas系列的最稳定方式.
BTW,squeeze = True参数暂时没用,因为截至今天(2013年4月)它只适用于面向行的CSV文件,请参阅官方文档:
http://pandas.pydata.org/pandas-docs/dev/io.html#returning-series
小智 5
这有效。挤压仍然有效,但它不会单独工作。在index_col需要设置为零,如下
series = pd.read_csv('csvfile.csv', header = None, index_col = 0, squeeze = True)
Run Code Online (Sandbox Code Playgroud)