2017-09-23 60 views
2

我正在研究一個項目,以讀取將由用戶生成的可變長度的文本文件。在文本文件的開頭有幾個註釋,其中一個需要用作列名。我知道可以用genfromtxt()來做到這一點,但我需要使用熊貓。以下是示例文本文件的開頭:使用熊貓閱讀行中的文本文件作爲列名

#GeneratedFile 
#This file will be generated by a user 
#a b c d f g h i j k l m n p q r s t v w x y z 
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 

我需要#a,b,c,...作爲列名。我嘗試了以下代碼行來讀取數據並將其更改爲數組,但它僅返回行並忽略了列名。

import pandas as pd  
data = pd.read_table('example.txt',header=2)  
d = pd.DataFrame.as_matrix(data) 

有沒有辦法做到這一點,而不使用genfromtxt()?

回答

0

一種方式可以嘗試以下操作:

df = pd.read_csv('example.txt', sep='\s+', engine='python', header=2) 

# the first column name become #a so, replacing the column name 
df.rename(columns={'#a':'a'}, inplace=True) 

# alternatively, other way is to replace # from all the column names 
#df.columns = [column_name.replace('#', '') for column_name in df.columns] 
print(df) 

結果:

a b c d f g h i j k ... p q r s t v w x y z 
0 0 1 2 3 4 5 6 7 8 9 ... 13 14 15 16 17 18 19 20 21 22 
1 1 2 3 4 5 6 7 8 9 10 ... 14 15 16 17 18 19 20 21 22 23 

[2 rows x 23 columns]