2016-11-23 21 views
7

Tôi đang làm một pandas DataFrame và tôi muốn giữ hàng đầu tiên, tuy nhiên nó tiếp tục chuyển đổi thành tên cột, tôi đã thử headers=False nhưng điều này chỉ xóa nó hoàn toàn.làm thế nào để ngăn chặn gấu trúc làm cho hàng đầu tiên vào tên cột

Tôi có một chuỗi (st = '\n'.join(lst)) mà tôi chuyển đổi thành đối tượng giống như tệp (io.StringIO(st)), sau đó xây dựng csv từ đối tượng tệp đó.

Trả lời

11

Bạn muốn header=None các False được gõ thăng int vào 0 thấy mỏ docs nhấn mạnh:

header : int or list of ints, default ‘infer’ Row number(s) to use as the column names, and the start of the data. Default behavior is as if set to 0 if no names passed, otherwise None. Explicitly pass header=0 to be able to replace existing names. The header can be a list of integers that specify row locations for a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines if skip_blank_lines=True, so header=0 denotes the first line of data rather than the first line of the file.

Bạn có thể thấy sự khác biệt trong hành vi, đầu tiên với header=0:

In [95]: 
import io 
import pandas as pd 
t="""a,b,c 
0,1,2 
3,4,5""" 
pd.read_csv(io.StringIO(t), header=0) 

Out[95]: 
    a b c 
0 0 1 2 
1 3 4 5 

Bây giờ với None:

In [96]: 
pd.read_csv(io.StringIO(t), header=None) 

Out[96]: 
    0 1 2 
0 a b c 
1 0 1 2 
2 3 4 5 

Lưu ý rằng trong phiên bản mới nhất 0.19.1, điều này bây giờ sẽ nâng cao một TypeError:

In [98]: 
pd.read_csv(io.StringIO(t), header=False) 

TypeError: Passing a bool to header is invalid. Use header=None for no header or header=int or list-like of ints to specify the row(s) making up the column names

5

tôi nghĩ rằng bạn cần tham số header=None-read_csv:

mẫu:

import pandas as pd 
from pandas.compat import StringIO 

temp=u"""a,b 
2,1 
1,1""" 

df = pd.read_csv(StringIO(temp),header=None) 
print (df) 
    0 1 
0 a b 
1 2 1 
2 1 1 
Các vấn đề liên quan