我有一个格式如下的 CSV 文件:
somefeature,anotherfeature,f3,f4,f5,f6,f7,lastfeature
0,0,0,1,1,2,4,5
我尝试将其作为 pandas 系列来阅读(使用 Python 2.7 的 pandas daily snapshot)。 我尝试了以下方法:
import pandas as pd
types = pd.Series.from_csv('csvfile.txt', index_col=False, header=0)
和:
types = pd.read_csv('csvfile.txt', index_col=False, header=0, squeeze=True)
但是两者都不起作用:第一个给出随机结果,第二个只是导入 DataFrame 而没有挤压。
pandas 似乎只能将 CSV 格式识别为系列:
f1, value
f2, value2
f3, value3
但是当功能键位于第一行而不是列时,pandas 不想挤压它。
还有什么我可以尝试的吗?这种行为是故意的吗?
这是我找到的方法:
df = pandas.read_csv('csvfile.txt', index_col=False, header=0);
serie = df.loc[0,:]
对我来说似乎有点愚蠢,因为 Squeeze 应该已经做到了这一点。这是一个错误还是我错过了什么?
/编辑:最好的方法:
df = pandas.read_csv('csvfile.txt', index_col=False, header=0);
serie = df.transpose()[0] # here we convert the DataFrame into a Serie
这是将面向行的 CSV 行放入 pandas Series 中最稳定的方法。
顺便说一句,squeeze=True 参数目前没用,因为截至今天(2013 年 4 月)它仅适用于面向行的 CSV 文件,请参阅官方文档:
http://pandas.pydata.org/pandas-docs/dev/io.html#returning-series
这有效。 Squeeze 仍然有效,但单独使用是行不通的。
index_col
需要设置为零,如下
series = pd.read_csv('csvfile.csv', header = None, index_col = 0, squeeze = True)
In [28]: df = pd.read_csv('csvfile.csv')
In [29]: df.ix[0]
Out[29]:
somefeature 0
anotherfeature 0
f3 0
f4 1
f5 1
f6 2
f7 4
lastfeature 5
Name: 0, dtype: int64
ds = pandas.read_csv('csvfile.csv', index_col=False, header=0);
X = ds.iloc[:, :10] #ix deprecated
Pandas 的值选择逻辑是:
DataFrame -> Series=DataFrame[Column] -> Values=Series[Index]
所以我建议:
df=pandas.read_csv("csvfile.csv")
s=df[df.columns[0]]
由于上面的答案都不适合我,所以这是另一个答案,从 DataFrame 手动重新创建系列。
# create example series
series = pd.Series([0, 1, 2], index=["a", "b", "c"])
series.index.name = "idx"
print(series)
print()
# create csv
series_csv = series.to_csv()
print(series_csv)
# read csv
df = pd.read_csv(io.StringIO(series_csv), index_col=0)
indx = df.index
vals = [df.iloc[i, 0] for i in range(len(indx))]
series_again = pd.Series(vals, index=indx)
print(series_again)
输出:
idx
a 0
b 1
c 2
dtype: int64
idx,0
a,0
b,1
c,2
idx
a 0
b 1
c 2
dtype: int64
from pandas import read_csv
series = read_csv('csvfile.csv', header=0, parse_dates=[0], index_col=0, squeeze=True