將表讀入 DataFrame

包含頁首,頁尾,行名稱和索引列的表檔案:

file:table.txt

This is a header that discusses the table file
to show space in a generic table file

index  name     occupation
1      Alice    Salesman
2      Bob      Engineer
3      Charlie  Janitor  

This is a footer because your boss does not understand data files

碼:

import pandas as pd
# index_col=0 tells pandas that column 0 is the index and not data 
pd.read_table('table.txt', delim_whitespace=True, skiprows=3, skipfooter=2, index_col=0)

輸出:

          name occupation
index
1        Alice   Salesman
2          Bob   Engineer
3      Charlie    Janitor

沒有行名或索引的表檔案:

file:table.txt

Alice    Salesman
Bob      Engineer
Charlie  Janitor 

碼:

import pandas as pd 
pd.read_table('table.txt', delim_whitespace=True, names=['name','occupation'])

輸出:

      name occupation
0    Alice   Salesman
1      Bob   Engineer
2  Charlie    Janitor

所有選項都可以在這裡的 pandas 文件中找到