2017-06-16 80 views
1

我有一些麻煩來讀取這樣的數據集:閱讀CSV與大熊貓有這種數據集

# title 
# description 
# link (could be not still active) 
# id 
# date 
# source (nyt|us|reuters) 
# category 

例如:

court agrees to expedite n.f.l.'s appeal\n 
the decision means a ruling could be made nearly two months before the regular season begins, time for the sides to work out a deal without delaying the 
season.\n 
http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/nbjo7ygxwpc/04nfl.html\n 
0\n 
04 May 2011 07:39:03\n 
nyt\n 
sport\n 

我想:

columns = ['title', 'description', 'link', 'id', 'date', 'source', 'category'] 
df = pd.read_csv('news', delimiter = "\n", names = columns,error_bad_lines=False) 

但它將所有信息放入列標題中。

有人知道一種方法來解決這個問題嗎?

謝謝!

回答

0

不能使用\n爲CSV分隔符,你可以做的是設置等於列名的索引,然後調換,即

df = pd.read_csv('news', index=columns).transpose() 
0

這裏有幾點需要注意:

1)長度超過1個字符的任何分隔符由Pandas解釋爲正則表達式。 2)由於'c'引擎不支持正則表達式,我已經明確地將引擎定義爲'python'來避免警告。

3)我不得不添加一個虛擬列,因爲在文件末尾有一個'\ n',後來我用drop刪除了該列。

因此,這些行將有望得到你想要的結果。

columns = ['title', 'description', 'link', 'id', 'date', 'source', 'category','dummy'] 
df = pd.read_csv('news', names=columns, delimiter="\\\\n", engine='python').drop('dummy',axis=1) 
df 

我希望這有助於:)