2015-05-18 144 views
2

熊貓我有#在標題行的CSV文件:閱讀CSV與評論標題

s = '#one two three\n1 2 3' 

如果我使用pd.read_csv#標誌進入第一頭:

import pandas as pd 
from io import StringIO 
pd.read_csv(StringIO(s), delim_whitespace=True) 
    #one two three 
0  1 2  3 

如果我設置參數comment='#',然後pandas完全忽略該行。

有沒有簡單的方法來處理這種情況?

第二個問題有關,是我怎麼能把手在這種情況下引用,它的工作原理沒有#

s = '"one one" two three\n1 2 3' 
print(pd.read_csv(StringIO(s), delim_whitespace=True)) 
    one one two three 
0  1 2  3 

它不與#

s = '#"one one" two three\n1 2 3' 
print(pd.read_csv(StringIO(s), delim_whitespace=True)) 
    #"one one" two three 
0  1  2 3 NaN 

謝謝!

++++++++++更新

這裏是用於第二實施例的測試。這樣

import pandas as pd 

from io import StringIO 
df = pd.read_csv(StringIO(s), delim_whitespace=True) 
new_name = df.columns[0].split("#")[0] 
df.rename(columns={df.columns[0]:new_name}) 
+1

難道你只是重命名錯誤的列名稱爲兩種情況?好像你濫用了'comment'參數,當它被設計爲忽略註釋行時,第二種情況下,我只是重命名它,沒有什麼大不了 – EdChum

+0

在第二種情況下我不能重命名,我有2列,一個名爲'#「一個,另一個名爲'one''。 –

回答

1

可以重命名read_csv()輸出的第一頭這樣是你需要加載整個文件在內存中,但它的工作原理。

+0

感謝這對第一個案件的作品,對第二個案件的任何建議?我有一個額外的'NaN'列 –

+0

你想重命名/刪除'NaN'列嗎? – farhawa

+0

不,在第二種情況下,我得到4列,第一個命名爲「#」,第二個「1」。重命名將不起作用。 –

1

您可以刪除你的文件的第一#:

s = u'#"one one" two three\n1 2 3' 

import pandas as pd 
from io import StringIO 

wholefile=StringIO(s).read().split("#")[1] 

pd.read_csv(StringIO(wholefile), delim_whitespace=True) 

    one one two three 
0  1 2  3 

的不便

s = '#"one one" two three\n1 2 3' 
# here I am cheating slicing the string 
wanted_result = pd.read_csv(StringIO(s[1:]), delim_whitespace=True) 
# is there a way to achieve the same result configuring somehow read_csv? 
assert wanted_result.equals(pd.read_csv(StringIO(s), delim_whitespace=True)) 
+0

好吧,如果沒有其他的作品這是好的! –