【问题标题】:How to read a pandas Series from a CSV file如何从 CSV 文件中读取熊猫系列
【发布时间】:2013-03-23 13:19:33
【问题描述】:

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

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

我尝试将其作为熊猫系列阅读(使用 Python 2.7 的熊猫每日快照)。 我尝试了以下方法:

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

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

【问题讨论】:

    标签: csv pandas series


    【解决方案1】:
    from pandas import read_csv
    
    
    series = read_csv('csvfile.csv', header=0, parse_dates=[0], index_col=0, squeeze=True
    

    【讨论】:

      【解决方案2】:

      由于 Pandas 值选择逻辑是:

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

      所以我建议:

      df=pandas.read_csv("csvfile.csv")
      s=df[df.columns[0]]
      

      【讨论】:

        【解决方案3】:

        这行得通。挤压仍然有效,但它不会单独工作。 index_col 需要设置为零,如下所示

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

        【讨论】:

          【解决方案4】:
          ds = pandas.read_csv('csvfile.csv', index_col=False, header=0);    
          X = ds.iloc[:, :10] #ix deprecated
          

          【讨论】:

            【解决方案5】:

            这是我找到的方法:

            df = pandas.read_csv('csvfile.txt', index_col=False, header=0);
            serie = df.ix[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 系列的最稳定方法。

            顺便说一句,squeeze=True 参数现在没用,因为截至今天(2013 年 4 月)它只适用于面向行的 CSV 文件,请参阅官方文档:

            http://pandas.pydata.org/pandas-docs/dev/io.html#returning-series

            【讨论】:

            • 这对我不起作用! transpose 函数将我的整个数据帧变成了一些奇怪的 2X2 对象。我还在努力解决这个问题
            【解决方案6】:
            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
            

            【讨论】:

              猜你喜欢
              • 2017-11-03
              • 2017-05-09
              • 1970-01-01
              • 2015-05-09
              • 2019-12-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多