将CSV文件导入为Pandas DataFrame。

132

如何将以下 CSV 文件读入 Pandas DataFrame 中?

Date,"price","factor_1","factor_2"
2012-06-11,1600.20,1.255,1.548
2012-06-12,1610.02,1.258,1.554
2012-06-13,1618.07,1.249,1.552
2012-06-14,1624.40,1.253,1.556
2012-06-15,1626.15,1.258,1.552
2012-06-16,1626.15,1.263,1.558
2012-06-17,1626.15,1.264,1.572
6个回答

216

pandas.read_csv 来拯救:

import pandas as pd
df = pd.read_csv("data.csv")
print(df)

这将输出一个 pandas 的 DataFrame
        Date    price  factor_1  factor_2
0  2012-06-11  1600.20     1.255     1.548
1  2012-06-12  1610.02     1.258     1.554
2  2012-06-13  1618.07     1.249     1.552
3  2012-06-14  1624.40     1.253     1.556
4  2012-06-15  1626.15     1.258     1.552
5  2012-06-16  1626.15     1.263     1.558
6  2012-06-17  1626.15     1.264     1.572

30
要将CSV文件读取为pandas DataFrame,您需要使用pd.read_csv,其中sep=','是默认值。
但这并不是故事的结束;数据以许多不同的格式存在,并以不同的方式存储,因此您通常需要传递其他参数给read_csv,以确保正确读取您的数据。
以下是列出了CSV文件中遇到的常见情况及所需使用的适当参数的表格。您通常需要使用以下所有或某些组合的参数来读取您的数据。
┌───────────────────────────────────────────────────────┬───────────────────────┬────────────────────────────────────────────────────┐
│ pandas Implementation                                 │ Argument              │ Description                                        │
├───────────────────────────────────────────────────────┼───────────────────────┼────────────────────────────────────────────────────┤
│ pd.read_csv(..., sep=';')                             │ sep/delimiter         │ Read CSV with different separator¹                 │
│ pd.read_csv(..., delim_whitespace=True)               │ delim_whitespace      │ Read CSV with tab/whitespace separator             │
│ pd.read_csv(..., encoding='latin-1')                  │ encoding              │ Fix UnicodeDecodeError while reading²              │
│ pd.read_csv(..., header=False, names=['x', 'y', 'z']) │ header and names      │ Read CSV without headers³                          │
│ pd.read_csv(..., index_col=[0])                       │ index_col             │ Specify which column to set as the index⁴          │
│ pd.read_csv(..., usecols=['x', 'y'])                  │ usecols               │ Read subset of columns                             │
│ pd.read_csv(..., thousands='.', decimal=',')          │ thousands and decimal │ Numeric data is in European format (eg., 1.234,56) │
└───────────────────────────────────────────────────────┴───────────────────────┴────────────────────────────────────────────────────┘

脚注

  1. 默认情况下,read_csv 使用 C 解析引擎以提高性能。C 解析器只能处理单个字符分隔符。如果您的 CSV 有多个字符分隔符,则需要修改代码以使用 'python' 引擎。您也可以传递正则表达式:

     df = pd.read_csv(..., sep=r'\s*\|\s*', engine='python')
    
  2. UnicodeDecodeError 发生在数据存储在一种编码格式中,但在不兼容的另一种编码格式中读取时。最常见的编码方案是 'utf-8''latin-1',您的数据可能适合其中之一。

  3. header=False 指定 CSV 中的第一行是数据行而不是标题行,names=[...] 允许您指定要在创建 DataFrame 时分配给其的列名列表。

  4. "Unnamed: 0" 出现在将具有未命名索引的 DataFrame 保存到 CSV 中,然后重新读取后。您可以在写入时使用以下方法来解决问题,而无需在读取时修复:

     df.to_csv(..., index=False)
    

这里还有其他的参数我没有提到,但是这些是你最常遇到的。


9

使用Python内置的csv模块可以替代pandas库。

import csv
from pprint import pprint
with open('foo.csv', 'rb') as f:
    reader = csv.reader(f)
    headers = reader.next()
    column = {h:[] for h in headers}
    for row in reader:
        for h, v in zip(headers, row):
            column[h].append(v)
    pprint(column)    # Pretty printer

将会打印

{'Date': ['2012-06-11',
          '2012-06-12',
          '2012-06-13',
          '2012-06-14',
          '2012-06-15',
          '2012-06-16',
          '2012-06-17'],
 'factor_1': ['1.255', '1.258', '1.249', '1.253', '1.258', '1.263', '1.264'],
 'factor_2': ['1.548', '1.554', '1.552', '1.556', '1.552', '1.558', '1.572'],
 'price': ['1600.20',
           '1610.02',
           '1618.07',
           '1624.40',
           '1626.15',
           '1626.15',
           '1626.15']}

第一版问题的具体要求是如何创建一个数据框,就像在R中所做的那样。这并没有回答被问到的问题。 - Trenton McKinney

7
import pandas as pd
df = pd.read_csv('/PathToFile.txt', sep = ',')

这将把你的 .txt 或 .csv 文件导入到一个数据框中。

-1
你可以使用 Python 标准库中的 csv 模块 来操作 CSV 文件。
例如:
import csv
with open('some.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row

1
从R转过来的mazlor不会寻找csv模块,因为它太低级了。pandas提供了所需的抽象级别。 - Steven Rumbalski
此外,它还将数据读入到一个有用的Python对象中,例如numpy数组。 - Paul Hiemstra

-2

虽然不太干净,但是:

import csv

with open("value.txt", "r") as f:
    csv_reader = reader(f)
    num = '  '
    for row in csv_reader:
        print num, '\t'.join(row)
        if num == '  ':  
            num=0
        num=num+1

虽然不够紧凑,但它能完成任务:

   Date price   factor_1    factor_2
1 2012-06-11    1600.20 1.255   1.548
2 2012-06-12    1610.02 1.258   1.554
3 2012-06-13    1618.07 1.249   1.552
4 2012-06-14    1624.40 1.253   1.556
5 2012-06-15    1626.15 1.258   1.552
6 2012-06-16    1626.15 1.263   1.558
7 2012-06-17    1626.15 1.264   1.572

2
这并没有回答 OP 的问题,因为它没有将 CSV 数据读入 Python 对象中。 - Paul Hiemstra
第一个问题版本特别询问如何像R一样创建DataFrame。这并没有回答所提出的问题。 - Trenton McKinney

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