2016-04-22 10 views
2

I持って、次のfile.txtなど(簡略):パンダ:read_csv示す 'スペース区切り'

SICcode  Catcode  Category        SICname  MultSIC 
0111  A1500  Wheat, corn, soybeans and cash grain  Wheat  X 
0112  A1600  Other commodities (incl rice, peanuts)  Rice  X 
0115  A1500  Wheat, corn, soybeans and cash grain  Corn  X 
0116  A1500  Wheat, corn, soybeans and cash grain  Soybeans  X 
0119  A1500  Wheat, corn, soybeans and cash grain  Cash grains, NEC  X 
0131  A1100  Cotton  Cotton  X 
0132  A1300  Tobacco & Tobacco products     Tobacco  X 

私はパンダのDFにそれを読んでいくつかの問題を抱えています。私は、次の仕様engine='python', sep='Tab'pd.read_csvを試みたが、それは1列にファイルを返しました:

SICcode Catcode Category SICname MultSIC 
0 0111 A1500 Wheat, corn, soybeans... 
1 0112 A1600 Other commodities (in... 
2 0115 A1500 Wheat, corn, soybeans... 
3 0116 A1500 Wheat, corn, soybeans... 

それから私は、区切り文字として「タブ」を使用してgnumericのファイルにそれを入れてみましたが、それは一つの列としてファイルを読みます。誰かがこれについてアイデアを持っていますか?

答えて

3

df = pd.read_csv('file.txt', sep='\t')一列を持つデータフレームを返した場合は、その後明らかにfile.txtセパレータとしてタブを使用していません。あなたのデータかもしれないかもしれないは単に区切り記号としてスペースを持っています。その場合は試してみてください

df = pd.read_csv('data', sep=r'\s{2,}') 

正規表現パターン\s{2,}をセパレータとして使用しています。この正規表現は、2つ以上の空白文字と一致します。

In [8]: df 
Out[8]: 
    SICcode Catcode        Category   SICname \ 
0  111 A1500 Wheat, corn, soybeans and cash grain    Wheat 
1  112 A1600 Other commodities (incl rice, peanuts)    Rice 
2  115 A1500 Wheat, corn, soybeans and cash grain    Corn 
3  116 A1500 Wheat, corn, soybeans and cash grain   Soybeans 
4  119 A1500 Wheat, corn, soybeans and cash grain Cash grains, NEC 
5  131 A1100         Cotton   Cotton 
6  132 A1300    Tobacco & Tobacco products   Tobacco 

    MultSIC 
0  X 
1  X 
2  X 
3  X 
4  X 
5  X 
6  X 

これが機能しない場合、print(repr(open(file.txt, 'rb').read(100))を投稿してください。これは、file.txtの最初の100バイトの明白な表現を示します。

+0

@ unutbu:それは働いた!ありがとう! –

1

csvのデータがTabulatorで区切られている場合は、sep="\t"read_csvに追加してみてください。

import pandas as pd 

df = pd.read_csv('test/a.csv', sep="\t") 
print df 
    SICcode Catcode        Category   SICname \ 
0  111 A1500 Wheat, corn, soybeans and cash grain    Wheat 
1  112 A1600 ther commodities (incl rice, peanuts)    Rice 
2  115 A1500 Wheat, corn, soybeans and cash grain    Corn 
3  116 A1500 Wheat, corn, soybeans and cash grain   Soybeans 
4  119 A1500 Wheat, corn, soybeans and cash grain Cash grains, NEC 
5  131 A1100         Cotton   Cotton 
6  132 A1300    Tobacco & Tobacco products   Tobacco 

    MultSIC 
0  X 
1  X 
2  X 
3  X 
4  X 
5  X 
6  X 
+0

私はあなたの提案を試み、1つの列にdfを返します。拡張子を 'csv'から' txt'に変更しようとします。 –

+1

さて、あなたは、いくつかのエディタでファイルを開くことができます。 notepad ++とカラムのセパレータをチェックします。それはタブですか?または空白のみですか? – jezrael

+0

8スペースのタブです。 –

関連する問題