如何从CSV文件读取pandas Series数据

16

我有一个格式如下的CSV文件:

somefeature,anotherfeature,f3,f4,f5,f6,f7,lastfeature
0,0,0,1,1,2,4,5

我尝试将其作为pandas Series读取(使用Python 2.7的pandas每日快照)。 我尝试了以下内容:

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不想压缩它。

我还有什么别的尝试吗?这种行为是有意的吗?

7个回答

16

这是我找到的方法:

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


那对我没用!转置函数把我的整个数据框变成了一些奇怪的 2X2 对象。我还在努力弄清楚这个问题。 - user3813620
这不再起作用,因为它已被删除。 - Tommy
@Tommy 谢谢,我已经相应地更新了我的答案。这些都是旧答案(这一个已经十年了),我不会把它们全部更新... - gaborous

12

这是可行的。Squeeze仍然有效,但它不能单独工作。如下所示,需要将index_col设置为零

series = pd.read_csv('csvfile.csv', header = None, index_col = 0, squeeze = True)

3
squeeze参数已自1.4.0版本起被弃用。文档提示:“在调用read_csv时附加.squeeze("columns")以压缩数据。” - cmosig

4
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

注意:已删除ix - Tommy

2
ds = pandas.read_csv('csvfile.csv', index_col=False, header=0);    
X = ds.iloc[:, :10] #ix deprecated

1
Pandas的值选择逻辑为:

DataFrame -> Series=DataFrame[Column] -> Values=Series[Index]

所以我建议:
df=pandas.read_csv("csvfile.csv")
s=df[df.columns[0]]

1
from pandas import read_csv


series = read_csv('csvfile.csv', header=0, parse_dates=[0], index_col=0, squeeze=True

1

由于上面的答案都对我无效,这里提供另一种方法:从DataFrame手动重建Series。

# 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接