Cách tạo bảng trong tệp văn bản bằng python

In the case of indexed data, you can pass the column number or column name you wish to use as the index

In [3]: pd.read_csv['foo.csv', index_col=0]
Out[3]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5

In [4]: pd.read_csv['foo.csv', index_col='date']
Out[4]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5

You can also use a list of columns to create a hierarchical index

In [5]: pd.read_csv['foo.csv', index_col=[0, 'A']]
Out[5]: 
            B  C
date     A      
20090101 a  1  2
20090102 b  3  4
20090103 c  4  5

The dialect keyword gives greater flexibility in specifying the file format. By default it uses the Excel dialect but you can specify either the dialect name or a csv. Dialect instance.

Suppose you had data with unenclosed quotes

In [6]: print[data]
label1,label2,label3
index1,"a,c,e
index2,b,d,f

By default, read_csv uses the Excel dialect and treats the double quote as the quote character, which causes it to fail when it finds a newline before it finds the closing double quote.

We can get around this using dialect

In [7]: dia = csv.excel[]

In [8]: dia.quoting = csv.QUOTE_NONE

In [9]: pd.read_csv[StringIO[data], dialect=dia]
Out[9]: 
       label1 label2 label3
index1     "a      c      e
index2      b      d      f

All of the dialect options can be specified separately by keyword arguments

In [10]: data = 'a,b,c~1,2,3~4,5,6'

In [11]: pd.read_csv[StringIO[data], lineterminator='~']
Out[11]: 
   a  b  c
0  1  2  3
1  4  5  6

Another common dialect option is skipinitialspace , to skip any whitespace after a delimiter.

In [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'

In [13]: print[data]
a, b, c
1, 2, 3
4, 5, 6

In [14]: pd.read_csv[StringIO[data], skipinitialspace=True]
Out[14]: 
   a  b  c
0  1  2  3
1  4  5  6

The parsers make every attempt to “do the right thing” and not be very fragile. Type inference is a pretty big deal. So if a column can be coerced to integer dtype without altering the contents, it will do so. Any non-numeric columns will come through as object dtype as with the rest of pandas objects

Specifying column data types¶

Starting with v0. 10, you can indicate the data type for the whole DataFrame or individual columns

In [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'

In [16]: print[data]
a,b,c
1,2,3
4,5,6
7,8,9

In [17]: df = pd.read_csv[StringIO[data], dtype=object]

In [18]: df
Out[18]: 
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

In [19]: df['a'][0]
Out[19]: '1'

In [20]: df = pd.read_csv[StringIO[data], dtype={'b': object, 'c': np.float64}]

In [21]: df.dtypes
Out[21]: 
a      int64
b     object
c    float64
dtype: object

Note

The dtype option is currently only supported by the C engine. Specifying dtype with engine other than ‘c’ raises a ValueError .

Handling column names¶

A file may or may not have a header row. pandas assumes the first row should be used as the column names

In [2]: pd.read_csv['foo.csv']
Out[2]: 
       date  A  B  C
0  20090101  a  1  2
1  20090102  b  3  4
2  20090103  c  4  5
0

By specifying the names argument in conjunction with header you can indicate other names to use and whether or not to throw away the header row [if any].

In [2]: pd.read_csv['foo.csv']
Out[2]: 
       date  A  B  C
0  20090101  a  1  2
1  20090102  b  3  4
2  20090103  c  4  5
1

If the header is in a row other than the first, pass the row number to header . This will skip the preceding rows.

In [2]: pd.read_csv['foo.csv']
Out[2]: 
       date  A  B  C
0  20090101  a  1  2
1  20090102  b  3  4
2  20090103  c  4  5
2

Filtering columns [ usecols

The usecols argument allows you to select any subset of the columns in a file, either using the column names or position numbers.

In [2]: pd.read_csv['foo.csv']
Out[2]: 
       date  A  B  C
0  20090101  a  1  2
1  20090102  b  3  4
2  20090103  c  4  5
3

Ignoring line comments and empty lines¶

If the comment parameter is specified, then completely commented lines will be ignored. By default, completely blank lines will be ignored as well. Both of these are API changes introduced in version 0. 15.

In [2]: pd.read_csv['foo.csv']
Out[2]: 
       date  A  B  C
0  20090101  a  1  2
1  20090102  b  3  4
2  20090103  c  4  5
4

If skip_blank_lines=False , then read_csv will not ignore blank lines.

In [2]: pd.read_csv['foo.csv']
Out[2]: 
       date  A  B  C
0  20090101  a  1  2
1  20090102  b  3  4
2  20090103  c  4  5
5

Warning

The presence of ignored lines might create ambiguities involving line numbers; the parameter header uses row numbers [ignoring commented/empty lines], while skiprows uses line numbers [including commented/empty lines].

In [2]: pd.read_csv['foo.csv']
Out[2]: 
       date  A  B  C
0  20090101  a  1  2
1  20090102  b  3  4
2  20090103  c  4  5
6

If both header and skiprows are specified, header will be relative to the end of skiprows . For example.

In [2]: pd.read_csv['foo.csv']
Out[2]: 
       date  A  B  C
0  20090101  a  1  2
1  20090102  b  3  4
2  20090103  c  4  5
7

Dealing with Unicode Data¶

The encoding argument should be used for encoded unicode data, which will result in byte strings being decoded to unicode in the result.

In [2]: pd.read_csv['foo.csv']
Out[2]: 
       date  A  B  C
0  20090101  a  1  2
1  20090102  b  3  4
2  20090103  c  4  5
8

Some formats which encode all characters as multiple bytes, like UTF-16, won’t parse correctly at all without specifying the encoding. Full list of Python standard encodings

Index columns and trailing delimiters¶

If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names

In [2]: pd.read_csv['foo.csv']
Out[2]: 
       date  A  B  C
0  20090101  a  1  2
1  20090102  b  3  4
2  20090103  c  4  5
9

In [3]: pd.read_csv['foo.csv', index_col=0]
Out[3]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
0

Thông thường, bạn có thể đạt được hành vi này bằng cách sử dụng tùy chọn index_col .

There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. Để vô hiệu hóa rõ ràng suy luận cột chỉ mục và loại bỏ cột cuối cùng, hãy vượt qua index_col=False .

In [3]: pd.read_csv['foo.csv', index_col=0]
Out[3]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
1

Chỉ định cột ngày¶

Để tạo điều kiện thuận lợi hơn khi làm việc với dữ liệu ngày giờ, read_csv[]read_table[] uses the keyword arguments parse_dates and date_parser to allow users to specify a variety of columns and date/time formats to turn the input text data into datetime objects.

Trường hợp đơn giản nhất là chỉ cần chuyển vào parse_dates=True .

In [3]: pd.read_csv['foo.csv', index_col=0]
Out[3]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
2

Chúng tôi thường muốn lưu trữ riêng dữ liệu ngày và giờ hoặc lưu trữ riêng các trường ngày khác nhau. từ khóa parse_dates có thể được sử dụng để chỉ định tổ hợp các cột nhằm phân tích ngày và/hoặc thời gian từ.

Bạn có thể chỉ định danh sách các danh sách cột cho parse_dates , các cột ngày kết quả sẽ được thêm vào đầu ra [để không ảnh hưởng đến .

In [3]: pd.read_csv['foo.csv', index_col=0]
Out[3]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
3

Theo mặc định, trình phân tích cú pháp sẽ xóa các cột ngày của thành phần nhưng bạn có thể chọn giữ lại chúng thông qua từ khóa keep_date_col .

In [3]: pd.read_csv['foo.csv', index_col=0]
Out[3]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
4

Lưu ý rằng nếu bạn muốn kết hợp nhiều cột thành một cột ngày, thì phải sử dụng danh sách lồng nhau. Nói cách khác, parse_dates=[1, 2] chỉ ra rằng mỗi cột thứ hai và thứ ba phải được phân tích cú pháp thành . parse_dates=[[1, 2]] means the two columns should be parsed into a single column.

Bạn cũng có thể sử dụng lệnh để chỉ định các cột tên tùy chỉnh

In [3]: pd.read_csv['foo.csv', index_col=0]
Out[3]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
5

It is important to remember that if multiple text columns are to be parsed into a single date column, then a new column is prepended to the data. The index_col specification is based off of this new set of columns rather than the original data columns

In [3]: pd.read_csv['foo.csv', index_col=0]
Out[3]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
6

Note

read_csv has a fast_path for parsing datetime strings in iso8601 format, e. g “2000-01-01T00. 01. 02+00. 00” and similar variations. If you can arrange for your data to store datetimes in this format, load times will be significantly faster, ~20x has been observed

Note

When passing a dict as the parse_dates argument, the order of the columns prepended is not guaranteed, because dict objects do not impose an ordering on their keys. On Python 2. 7+ you may use collections. OrderedDict instead of a regular dict if this matters to you. Because of this, when using a dict for ‘parse_dates’ in conjunction with the index_col argument, it’s best to specify index_col as a column label rather then as an index on the resulting frame

Specifying method for floating-point conversion¶

The parameter float_precision can be specified in order to use a specific floating-point converter during parsing with the C engine. The options are the ordinary converter, the high-precision converter, and the round-trip converter [which is guaranteed to round-trip values after writing to a file]. For example.

In [3]: pd.read_csv['foo.csv', index_col=0]
Out[3]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
7

Date Parsing Functions¶

Finally, the parser allows you can specify a custom date_parser function to take full advantage of the flexibility of the date parsing API.

In [3]: pd.read_csv['foo.csv', index_col=0]
Out[3]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
8

You can explore the date parsing functionality in date_converters. py and add your own. We would love to turn this module into a community supported set of date/time parsers. To get you started, date_converters. py contains functions to parse dual date and time columns, year/month/day columns, and year/month/day/hour/minute/second columns. It also contains a generic_parser function so you can curry it with a function that deals with a single date rather than the entire array.

Inferring Datetime Format¶

Nếu bạn đã bật parse_dates cho một số hoặc tất cả các cột của mình và tất cả các chuỗi ngày giờ của bạn đều được định dạng theo cùng một cách, bạn có thể nhận được . If set, pandas will attempt to guess the format of your datetime strings, and then use a faster means of parsing the strings. Tốc độ phân tích cú pháp 5-10 lần đã được quan sát. pandas will fallback to the usual parsing if either the format cannot be guessed or the format that was guessed cannot properly parse the entire column of strings. So in general, infer_datetime_format=True. If set, pandas will attempt to guess the format of your datetime strings, and then use a faster means of parsing the strings. 5-10x parsing speeds have been observed. pandas will fallback to the usual parsing if either the format cannot be guessed or the format that was guessed cannot properly parse the entire column of strings. So in general, infer_datetime_format should not have any negative consequences if enabled.

Here are some examples of datetime strings that can be guessed [All representing December 30th, 2011 at 00. 00. 00]

  • “20111230”
  • “2011/12/30”
  • “20111230 00. 00. 00”
  • “12/30/2011 00. 00. 00”
  • “30/Dec/2011 00. 00. 00”
  • “30/December/2011 00. 00. 00”

infer_datetime_format is sensitive to dayfirst . With dayfirst=True , it will guess “01/12/2011” to be December 1st. With dayfirst=False [default] it will guess “01/12/2011” to be January 12th.

In [3]: pd.read_csv['foo.csv', index_col=0]
Out[3]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
9

International Date Formats¶

While US date formats tend to be MM/DD/YYYY, many international formats use DD/MM/YYYY instead. For convenience, a dayfirst keyword is provided.

In [4]: pd.read_csv['foo.csv', index_col='date']
Out[4]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
0

Dấu Phân Cách Ngàn¶

Đối với những số lớn đã được viết bằng dấu tách hàng nghìn, bạn có thể đặt từ khóa nghìn thành một chuỗi có độ dài 1 sao cho các số nguyên .

Theo mặc định, các số có dấu tách hàng nghìn sẽ được phân tích thành chuỗi

In [4]: pd.read_csv['foo.csv', index_col='date']
Out[4]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
1

Từ khóa nghìn cho phép số nguyên được phân tích cú pháp chính xác

In [4]: pd.read_csv['foo.csv', index_col='date']
Out[4]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
2

Giá trị NA¶

Để kiểm soát giá trị nào được phân tích cú pháp dưới dạng giá trị bị thiếu [được biểu thị bằng NaN ], hãy chỉ định danh sách chuỗi trong na_values. If you specify a number [a float , như 5. 0 hoặc một số nguyên như 5], the corresponding equivalent values will also imply a missing value [in this case effectively [5.0,5] được công nhận là NaN .

To completely override the default values that are recognized as missing, specify keep_default_na=False . Các giá trị được công nhận NaN mặc định là ['-1. #IND', '1. #QNAN', '1. #IND', '-1. #QNAN', '#N/A','N/A', 'NA', '# . 'NULL', 'NaN', '-NaN', 'nan', '-nan'].

In [4]: pd.read_csv['foo.csv', index_col='date']
Out[4]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
3

các giá trị mặc định, ngoài 5 , 5. 0 khi được hiểu là số được nhận dạng là NaN

In [4]: pd.read_csv['foo.csv', index_col='date']
Out[4]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
4

chỉ một trường trống sẽ là NaN

In [4]: pd.read_csv['foo.csv', index_col='date']
Out[4]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
5

chỉ NA0 là chuỗi [cột], dữ liệu -> [giá trị]} bản ghi< . , {column -> value}]list like [{column -> value}, .. , {column -> value}]index dict like {index -> {column -> value}} columnsdict like {column -> {index -> value}}valuesjust the values array

  • date_format . chuỗi, loại chuyển đổi ngày, 'epoch' cho dấu thời gian, 'iso' cho ISO8601.

  • double_precision . Số vị trí thập phân sẽ sử dụng khi mã hóa các giá trị dấu phẩy động, mặc định là 10.

  • force_ascii . buộc chuỗi được mã hóa thành ASCII, mặc định là True.

  • date_unit . Đơn vị thời gian để mã hóa, chi phối dấu thời gian và độ chính xác ISO8601. Một trong số 's', 'ms', 'us' hoặc 'ns' tương ứng với giây, mili giây, micro giây và nano giây. 'ms' mặc định.

  • default_handler . Trình xử lý để gọi nếu một đối tượng không thể được chuyển đổi sang định dạng phù hợp cho JSON. Nhận một đối số duy nhất, là đối tượng cần chuyển đổi và trả về một đối tượng có thể tuần tự hóa.

  • Lưu ý NaN , NaT và . None will be converted to null and datetime objects will be converted based on the date_format and date_unit parameters.

    In [7]: dia = csv.excel[]
    
    In [8]: dia.quoting = csv.QUOTE_NONE
    
    In [9]: pd.read_csv[StringIO[data], dialect=dia]
    Out[9]: 
           label1 label2 label3
    index1     "a      c      e
    index2      b      d      f
    
    0

    Tùy chọn định hướng¶

    Có một số tùy chọn khác nhau cho định dạng của tệp/chuỗi JSON kết quả. Hãy xem xét DataFrame và Sê-ri sau

    In [7]: dia = csv.excel[]
    
    In [8]: dia.quoting = csv.QUOTE_NONE
    
    In [9]: pd.read_csv[StringIO[data], dialect=dia]
    Out[9]: 
           label1 label2 label3
    index1     "a      c      e
    index2      b      d      f
    
    1

    Hướng cột [mặc định cho DataFrame ] tuần tự hóa dữ liệu dưới dạng các đối tượng JSON lồng nhau với các nhãn cột đóng vai trò là chỉ mục chính.

    In [7]: dia = csv.excel[]
    
    In [8]: dia.quoting = csv.QUOTE_NONE
    
    In [9]: pd.read_csv[StringIO[data], dialect=dia]
    Out[9]: 
           label1 label2 label3
    index1     "a      c      e
    index2      b      d      f
    
    2

    Hướng chỉ mục [mặc định cho Sê-ri ] tương tự như hướng cột nhưng nhãn chỉ mục hiện là chính.

    In [7]: dia = csv.excel[]
    
    In [8]: dia.quoting = csv.QUOTE_NONE
    
    In [9]: pd.read_csv[StringIO[data], dialect=dia]
    Out[9]: 
           label1 label2 label3
    index1     "a      c      e
    index2      b      d      f
    
    3

    Record oriented serializes the data to a JSON array of column -> value records, index labels are not included. This is useful for passing DataFrame data to plotting libraries, for example the JavaScript library d3. js

    In [7]: dia = csv.excel[]
    
    In [8]: dia.quoting = csv.QUOTE_NONE
    
    In [9]: pd.read_csv[StringIO[data], dialect=dia]
    Out[9]: 
           label1 label2 label3
    index1     "a      c      e
    index2      b      d      f
    
    4

    Value oriented is a bare-bones option which serializes to nested JSON arrays of values only, column and index labels are not included

    In [7]: dia = csv.excel[]
    
    In [8]: dia.quoting = csv.QUOTE_NONE
    
    In [9]: pd.read_csv[StringIO[data], dialect=dia]
    Out[9]: 
           label1 label2 label3
    index1     "a      c      e
    index2      b      d      f
    
    5

    Split oriented serializes to a JSON object containing separate entries for values, index and columns. Name is also included for Series .

    In [7]: dia = csv.excel[]
    
    In [8]: dia.quoting = csv.QUOTE_NONE
    
    In [9]: pd.read_csv[StringIO[data], dialect=dia]
    Out[9]: 
           label1 label2 label3
    index1     "a      c      e
    index2      b      d      f
    
    6

    Note

    Any orient option that encodes to a JSON object will not preserve the ordering of index and column labels during round-trip serialization. If you wish to preserve label ordering use the split option as it uses ordered containers

    Date Handling¶

    Writing in ISO date format

    In [7]: dia = csv.excel[]
    
    In [8]: dia.quoting = csv.QUOTE_NONE
    
    In [9]: pd.read_csv[StringIO[data], dialect=dia]
    Out[9]: 
           label1 label2 label3
    index1     "a      c      e
    index2      b      d      f
    
    7

    Writing in ISO date format, with microseconds

    In [7]: dia = csv.excel[]
    
    In [8]: dia.quoting = csv.QUOTE_NONE
    
    In [9]: pd.read_csv[StringIO[data], dialect=dia]
    Out[9]: 
           label1 label2 label3
    index1     "a      c      e
    index2      b      d      f
    
    8

    Epoch timestamps, in seconds

    In [7]: dia = csv.excel[]
    
    In [8]: dia.quoting = csv.QUOTE_NONE
    
    In [9]: pd.read_csv[StringIO[data], dialect=dia]
    Out[9]: 
           label1 label2 label3
    index1     "a      c      e
    index2      b      d      f
    
    9

    Writing to a file, with a date index and a date column

    In [10]: data = 'a,b,c~1,2,3~4,5,6'
    
    In [11]: pd.read_csv[StringIO[data], lineterminator='~']
    Out[11]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    0

    Fallback Behavior¶

    If the JSON serializer cannot handle the container contents directly it will fallback in the following manner

    • if a toDict method is defined by the unrecognised object then that will be called and its returned dict will be JSON serialized.
    • if a default_handler has been passed to to_json that will be called to convert the object.
    • otherwise an attempt is made to convert the object to a dict by parsing its contents. However if the object is complex this will often fail with an OverflowError .

    Your best bet when encountering OverflowError during serialization is to specify a default_handler . For example timedelta can cause problems.

    In [10]: data = 'a,b,c~1,2,3~4,5,6'
    
    In [11]: pd.read_csv[StringIO[data], lineterminator='~']
    Out[11]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    1

    which can be dealt with by specifying a simple default_handler .

    In [10]: data = 'a,b,c~1,2,3~4,5,6'
    
    In [11]: pd.read_csv[StringIO[data], lineterminator='~']
    Out[11]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    2

    Reading JSON¶

    Reading a JSON string to pandas object can take a number of parameters. Trình phân tích cú pháp sẽ cố phân tích một DataFrame nếu typ không được cung cấp hoặc . To explicitly force None. To explicitly force Series parsing, pass typ=series

    • filepath_or_buffer . a VALID JSON string or file handle / StringIO. The string could be a URL. Valid URL schemes include http, ftp, S3, and file. For file URLs, a host is expected. For instance, a local file could be file . //localhost/path/to/table. json

    • typ . type of object to recover [series or frame], default ‘frame’

    • định hướng .

      Loạt
      • mặc định là chỉ mục
      • các giá trị được phép là { chia , bản ghi , < index}
      Khung dữ liệu
      • mặc định là cột
      • các giá trị được phép là { chia , bản ghi , < index, columns, values}

      Định dạng của chuỗi JSON

      chia dict như {chỉ mục -> [chỉ mục], cột -> [cột], dữ liệu -> [giá trị]} bản ghi< . , {column -> value}]list like [{column -> value}, .. , {column -> value}]index dict like {index -> {column -> value}} columnsdict like {column -> {index -> value}}valuesjust the values array
    • dtype . if True, infer dtypes, if a dict of column to dtype, then use those, if False, then don’t infer dtypes at all, default is True, apply only to the data

    • convert_axes . boolean, hãy thử chuyển đổi các trục thành các kiểu phù hợp, mặc định là True

    • convert_dates . một danh sách các cột để phân tích ngày tháng;

    • keep_default_dates . boolean, mặc định Đúng. Nếu phân tích cú pháp ngày, thì hãy phân tích cú pháp các cột giống như ngày tháng mặc định

    • numpy . giải mã trực tiếp đến mảng numpy. mặc định là Sai; . Cũng lưu ý rằng thứ tự JSON PHẢI giống nhau cho mỗi thuật ngữ nếu numpy=True

    • precise_float . boolean, mặc định Sai . Đặt để cho phép sử dụng hàm có độ chính xác cao hơn [strtod] khi giải mã chuỗi thành giá trị kép. Mặc định [ Sai ] là sử dụng chức năng dựng sẵn nhanh nhưng kém chính xác hơn

    • date_unit . chuỗi, đơn vị dấu thời gian để phát hiện nếu chuyển đổi ngày. Mặc định Không có. Theo mặc định, độ chính xác của dấu thời gian sẽ được phát hiện, nếu điều này không được mong muốn thì hãy chuyển một trong số 's', 'ms', 'us' hoặc 'ns' để buộc độ chính xác của dấu thời gian thành giây, mili giây, micro giây hoặc nano giây tương ứng.

    Trình phân tích cú pháp sẽ đưa ra một trong số ValueError/TypeError/AssertionError nếu JSON không thể phân tích cú pháp.

    Nếu một định hướng không mặc định không được sử dụng khi mã hóa thành JSON, hãy chắc chắn chuyển tùy chọn tương tự ở đây để quá trình giải mã tạo ra kết quả hợp lý, .

    Chuyển đổi dữ liệu¶

    Mặc định của convert_axes=True , dtype=True, and convert_dates=True will try to parse the axes, and all of the data into appropriate types, including dates. If you need to override specific dtypes, pass a dict to dtype . convert_axes chỉ nên được đặt thành False nếu bạn cần giữ nguyên chuỗi- . g. '1', '2'] trong một trục.

    Note

    Các giá trị số nguyên lớn có thể được chuyển đổi thành ngày nếu convert_dates=True và dữ liệu và/hoặc nhãn cột xuất hiện 'giống ngày'. Ngưỡng chính xác phụ thuộc vào date_unit được chỉ định.

    Warning

    Khi đọc dữ liệu JSON, việc tự động ép buộc vào dtypes có một số điều kỳ quặc

    • một chỉ mục có thể được xây dựng lại theo thứ tự khác với thứ tự tuần tự hóa, nghĩa là thứ tự trả về không được đảm bảo giống như trước khi tuần tự hóa
    • cột có dữ liệu float sẽ được chuyển thành số nguyên if it can be done safely, e.g. a column of 1.
    • các cột bool sẽ được chuyển đổi thành số nguyên khi xây dựng lại

    Do đó, có những lúc bạn có thể muốn chỉ định các loại dtype cụ thể thông qua đối số từ khóa dtype .

    Đọc từ một chuỗi JSON

    In [10]: data = 'a,b,c~1,2,3~4,5,6'
    
    In [11]: pd.read_csv[StringIO[data], lineterminator='~']
    Out[11]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    3

    Đọc từ một tập tin

    In [10]: data = 'a,b,c~1,2,3~4,5,6'
    
    In [11]: pd.read_csv[StringIO[data], lineterminator='~']
    Out[11]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    4

    Không chuyển đổi bất kỳ dữ liệu nào [nhưng vẫn chuyển đổi trục và ngày tháng]

    In [10]: data = 'a,b,c~1,2,3~4,5,6'
    
    In [11]: pd.read_csv[StringIO[data], lineterminator='~']
    Out[11]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    5

    Chỉ định dtypes để chuyển đổi

    In [10]: data = 'a,b,c~1,2,3~4,5,6'
    
    In [11]: pd.read_csv[StringIO[data], lineterminator='~']
    Out[11]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    6

    Giữ nguyên chỉ số chuỗi

    In [10]: data = 'a,b,c~1,2,3~4,5,6'
    
    In [11]: pd.read_csv[StringIO[data], lineterminator='~']
    Out[11]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    7

    Ngày được viết bằng nano giây cần được đọc lại bằng nano giây

    In [10]: data = 'a,b,c~1,2,3~4,5,6'
    
    In [11]: pd.read_csv[StringIO[data], lineterminator='~']
    Out[11]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    8

    Tham số Numpy¶

    Note

    Điều này chỉ hỗ trợ dữ liệu số. Nhãn chỉ mục và cột có thể không phải là số, e. g. chuỗi, ngày vv

    Nếu numpy=True được chuyển đến read_json an .

    Điều này có thể cung cấp khả năng tăng tốc nếu bạn đang giải tuần tự hóa một lượng lớn dữ liệu số

    In [10]: data = 'a,b,c~1,2,3~4,5,6'
    
    In [11]: pd.read_csv[StringIO[data], lineterminator='~']
    Out[11]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    9

    In [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
    
    In [13]: print[data]
    a, b, c
    1, 2, 3
    4, 5, 6
    
    In [14]: pd.read_csv[StringIO[data], skipinitialspace=True]
    Out[14]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    0

    In [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
    
    In [13]: print[data]
    a, b, c
    1, 2, 3
    4, 5, 6
    
    In [14]: pd.read_csv[StringIO[data], skipinitialspace=True]
    Out[14]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    1

    Việc tăng tốc ít được chú ý hơn đối với các bộ dữ liệu nhỏ hơn

    In [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
    
    In [13]: print[data]
    a, b, c
    1, 2, 3
    4, 5, 6
    
    In [14]: pd.read_csv[StringIO[data], skipinitialspace=True]
    Out[14]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    2

    In [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
    
    In [13]: print[data]
    a, b, c
    1, 2, 3
    4, 5, 6
    
    In [14]: pd.read_csv[StringIO[data], skipinitialspace=True]
    Out[14]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    3

    In [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
    
    In [13]: print[data]
    a, b, c
    1, 2, 3
    4, 5, 6
    
    In [14]: pd.read_csv[StringIO[data], skipinitialspace=True]
    Out[14]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    4

    Warning

    Giải mã numpy trực tiếp đưa ra một số giả định và có thể thất bại hoặc tạo ra kết quả không mong muốn nếu những giả định này không được thỏa mãn

    • dữ liệu là số
    • dữ liệu đồng nhất. dtype được đánh hơi từ giá trị đầu tiên được giải mã. Lỗi giá trị có thể tăng lên hoặc đầu ra không chính xác có thể được tạo ra nếu điều kiện này không được thỏa mãn.
    • các nhãn được sắp xếp. Nhãn chỉ được đọc từ vùng chứa đầu tiên, giả định rằng mỗi hàng/cột tiếp theo đã được mã hóa theo cùng một thứ tự. Điều này sẽ được đáp ứng nếu dữ liệu được mã hóa bằng cách sử dụng to_json nhưng có thể không đúng nếu JSON đến từ một nguồn khác.

    Chuẩn hóa¶

    Mới trong phiên bản 0. 13. 0

    gấu trúc cung cấp một chức năng tiện ích để lấy một lệnh hoặc danh sách các lệnh và chuẩn hóa dữ liệu bán cấu trúc này thành một bảng phẳng

    In [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
    
    In [13]: print[data]
    a, b, c
    1, 2, 3
    4, 5, 6
    
    In [14]: pd.read_csv[StringIO[data], skipinitialspace=True]
    Out[14]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    5

    HTML¶

    Đọc nội dung HTML¶

    Warning

    Chúng tôi đặc biệt khuyến khích bạn đọc các vấn đề phân tích cú pháp HTML liên quan đến các vấn đề xung quanh trình phân tích cú pháp BeautifulSoup4/html5lib/lxml

    Mới trong phiên bản 0. 12. 0

    Hàm read_html[] cấp cao nhất có thể chấp nhận một chuỗi/tệp/URL HTML và sẽ phân tích các bảng HTML thành danh sách các Khung dữ liệu gấu trúc. Hãy xem xét một vài ví dụ.

    Note

    read_html trả về danh sách của DataFrame objects, even if there is only a single table contained in the HTML content

    Đọc một URL không có tùy chọn

    In [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
    
    In [13]: print[data]
    a, b, c
    1, 2, 3
    4, 5, 6
    
    In [14]: pd.read_csv[StringIO[data], skipinitialspace=True]
    Out[14]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    6

    Note

    Dữ liệu từ URL trên thay đổi vào Thứ Hai hàng tuần nên dữ liệu kết quả ở trên và dữ liệu bên dưới có thể hơi khác một chút

    Đọc nội dung của tệp từ URL trên và chuyển nó tới read_html dưới dạng chuỗi

    In [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
    
    In [13]: print[data]
    a, b, c
    1, 2, 3
    4, 5, 6
    
    In [14]: pd.read_csv[StringIO[data], skipinitialspace=True]
    Out[14]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    7

    Bạn thậm chí có thể chuyển vào phiên bản StringIO nếu bạn muốn

    In [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
    
    In [13]: print[data]
    a, b, c
    1, 2, 3
    4, 5, 6
    
    In [14]: pd.read_csv[StringIO[data], skipinitialspace=True]
    Out[14]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    8

    Note

    Các ví dụ sau đây không được trình đánh giá IPython chạy do thực tế là có quá nhiều chức năng truy cập mạng làm chậm quá trình xây dựng tài liệu. Nếu bạn phát hiện lỗi hoặc một ví dụ không chạy, vui lòng báo cáo lỗi đó trên trang vấn đề GitHub của gấu trúc

    Đọc một URL và khớp với một bảng có chứa văn bản cụ thể

    In [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
    
    In [13]: print[data]
    a, b, c
    1, 2, 3
    4, 5, 6
    
    In [14]: pd.read_csv[StringIO[data], skipinitialspace=True]
    Out[14]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    
    9

    Chỉ định một hàng tiêu đề [theo mặc định, các phần tử được sử dụng để tạo chỉ mục cột]; . elements].

    In [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
    
    In [16]: print[data]
    a,b,c
    1,2,3
    4,5,6
    7,8,9
    
    In [17]: df = pd.read_csv[StringIO[data], dtype=object]
    
    In [18]: df
    Out[18]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    2  7  8  9
    
    In [19]: df['a'][0]
    Out[19]: '1'
    
    In [20]: df = pd.read_csv[StringIO[data], dtype={'b': object, 'c': np.float64}]
    
    In [21]: df.dtypes
    Out[21]: 
    a      int64
    b     object
    c    float64
    dtype: object
    
    0

    Chỉ định một cột chỉ mục

    In [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
    
    In [16]: print[data]
    a,b,c
    1,2,3
    4,5,6
    7,8,9
    
    In [17]: df = pd.read_csv[StringIO[data], dtype=object]
    
    In [18]: df
    Out[18]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    2  7  8  9
    
    In [19]: df['a'][0]
    Out[19]: '1'
    
    In [20]: df = pd.read_csv[StringIO[data], dtype={'b': object, 'c': np.float64}]
    
    In [21]: df.dtypes
    Out[21]: 
    a      int64
    b     object
    c    float64
    dtype: object
    
    1

    Chỉ định một số hàng để bỏ qua

    In [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
    
    In [16]: print[data]
    a,b,c
    1,2,3
    4,5,6
    7,8,9
    
    In [17]: df = pd.read_csv[StringIO[data], dtype=object]
    
    In [18]: df
    Out[18]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    2  7  8  9
    
    In [19]: df['a'][0]
    Out[19]: '1'
    
    In [20]: df = pd.read_csv[StringIO[data], dtype={'b': object, 'c': np.float64}]
    
    In [21]: df.dtypes
    Out[21]: 
    a      int64
    b     object
    c    float64
    dtype: object
    
    2

    Chỉ định một số hàng cần bỏ qua bằng cách sử dụng danh sách [ xrange [chỉ Python 2] cũng hoạt động]

    In [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
    
    In [16]: print[data]
    a,b,c
    1,2,3
    4,5,6
    7,8,9
    
    In [17]: df = pd.read_csv[StringIO[data], dtype=object]
    
    In [18]: df
    Out[18]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    2  7  8  9
    
    In [19]: df['a'][0]
    Out[19]: '1'
    
    In [20]: df = pd.read_csv[StringIO[data], dtype={'b': object, 'c': np.float64}]
    
    In [21]: df.dtypes
    Out[21]: 
    a      int64
    b     object
    c    float64
    dtype: object
    
    3

    Không suy ra các kiểu số và ngày

    In [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
    
    In [16]: print[data]
    a,b,c
    1,2,3
    4,5,6
    7,8,9
    
    In [17]: df = pd.read_csv[StringIO[data], dtype=object]
    
    In [18]: df
    Out[18]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    2  7  8  9
    
    In [19]: df['a'][0]
    Out[19]: '1'
    
    In [20]: df = pd.read_csv[StringIO[data], dtype={'b': object, 'c': np.float64}]
    
    In [21]: df.dtypes
    Out[21]: 
    a      int64
    b     object
    c    float64
    dtype: object
    
    4

    Chỉ định một thuộc tính HTML

    In [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
    
    In [16]: print[data]
    a,b,c
    1,2,3
    4,5,6
    7,8,9
    
    In [17]: df = pd.read_csv[StringIO[data], dtype=object]
    
    In [18]: df
    Out[18]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    2  7  8  9
    
    In [19]: df['a'][0]
    Out[19]: '1'
    
    In [20]: df = pd.read_csv[StringIO[data], dtype={'b': object, 'c': np.float64}]
    
    In [21]: df.dtypes
    Out[21]: 
    a      int64
    b     object
    c    float64
    dtype: object
    
    5

    Sử dụng một số kết hợp ở trên

    In [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
    
    In [16]: print[data]
    a,b,c
    1,2,3
    4,5,6
    7,8,9
    
    In [17]: df = pd.read_csv[StringIO[data], dtype=object]
    
    In [18]: df
    Out[18]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    2  7  8  9
    
    In [19]: df['a'][0]
    Out[19]: '1'
    
    In [20]: df = pd.read_csv[StringIO[data], dtype={'b': object, 'c': np.float64}]
    
    In [21]: df.dtypes
    Out[21]: 
    a      int64
    b     object
    c    float64
    dtype: object
    
    6

    Đọc bằng gấu trúc to_html [với một số mất độ chính xác của dấu phẩy động]

    In [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
    
    In [16]: print[data]
    a,b,c
    1,2,3
    4,5,6
    7,8,9
    
    In [17]: df = pd.read_csv[StringIO[data], dtype=object]
    
    In [18]: df
    Out[18]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    2  7  8  9
    
    In [19]: df['a'][0]
    Out[19]: '1'
    
    In [20]: df = pd.read_csv[StringIO[data], dtype={'b': object, 'c': np.float64}]
    
    In [21]: df.dtypes
    Out[21]: 
    a      int64
    b     object
    c    float64
    dtype: object
    
    7

    Phần phụ trợ lxml sẽ gây ra lỗi khi phân tích cú pháp không thành công nếu đó là trình phân tích cú pháp duy nhất bạn cung cấp [nếu bạn chỉ có một trình phân tích cú pháp duy nhất

    In [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
    
    In [16]: print[data]
    a,b,c
    1,2,3
    4,5,6
    7,8,9
    
    In [17]: df = pd.read_csv[StringIO[data], dtype=object]
    
    In [18]: df
    Out[18]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    2  7  8  9
    
    In [19]: df['a'][0]
    Out[19]: '1'
    
    In [20]: df = pd.read_csv[StringIO[data], dtype={'b': object, 'c': np.float64}]
    
    In [21]: df.dtypes
    Out[21]: 
    a      int64
    b     object
    c    float64
    dtype: object
    
    8

    hoặc

    In [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
    
    In [16]: print[data]
    a,b,c
    1,2,3
    4,5,6
    7,8,9
    
    In [17]: df = pd.read_csv[StringIO[data], dtype=object]
    
    In [18]: df
    Out[18]: 
       a  b  c
    0  1  2  3
    1  4  5  6
    2  7  8  9
    
    In [19]: df['a'][0]
    Out[19]: '1'
    
    In [20]: df = pd.read_csv[StringIO[data], dtype={'b': object, 'c': np.float64}]
    
    In [21]: df.dtypes
    Out[21]: 
    a      int64
    b     object
    c    float64
    dtype: object
    
    9

    Tuy nhiên, nếu bạn đã cài đặt bs4 và html5lib và vượt qua Không có hoặc ['lxml', . Lưu ý rằng ngay sau khi phân tích cú pháp thành công, hàm sẽ trả về. 'bs4'] then the parse will most likely succeed. Note that as soon as a parse succeeds, the function will return.

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    00

    Ghi vào tệp HTML¶

    DataFrame có một phương thức thể hiện to_html để hiển thị nội dung của DataFrame as an HTML table. The function arguments are as in the method to_string được mô tả ở trên.

    Note

    Không phải tất cả các tùy chọn có thể có cho DataFrame. to_html được hiển thị ở đây vì mục đích ngắn gọn. Xem to_html[] để biết đầy đủ các tùy chọn.

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    01

    HTML

    010-0. 1847440. 4969711-0. 8562401. 857977

    Đối số cột sẽ giới hạn số cột được hiển thị

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    02

    HTML

    00-0. 1847441-0. 856240

    float_format sử dụng Python có thể gọi được để kiểm soát độ chính xác của các giá trị dấu phẩy động

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    03

    HTML

    010-0. 18474385760. 49697113271-0. 85623967631. 8579766508

    bold_rows sẽ in đậm nhãn hàng theo mặc định nhưng bạn có thể tắt tính năng này

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    04

    010-0. 1847440. 4969711-0. 8562401. 857977

    Đối số lớp cung cấp khả năng đưa ra các lớp CSS của bảng HTML kết quả. Lưu ý rằng các lớp này được thêm vào lớp 'dataframe' hiện có.

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    05

    Cuối cùng, đối số escape cho phép bạn kiểm soát xem các ký tự “ True]. So to get the HTML without escaped characters pass escape=False

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    06

    trốn thoát

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    07

    ab0&-0.4740631-0.400654

    không thoát

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    08

    ab0&-0.4740631-0.400654

    Note

    Một số trình duyệt có thể không hiển thị sự khác biệt trong kết xuất của hai bảng HTML trước đó

    Tệp Excel¶

    Phương thức read_excel[] có thể đọc Excel 2003 [ . xls ] và Excel 2007 [ . xlsx ] bằng cách sử dụng mô-đun xlrd Python và sử dụng cùng mã phân tích cú pháp như ở trên để chuyển đổi dữ liệu dạng bảng thành dạng . Xem sách dạy nấu ăn để biết một số chiến lược nâng cao

    Ngoài ra read_excel bạn cũng có thể đọc các tệp Excel bằng cách sử dụng ExcelFile class. The following two commands are equivalent:

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    09

    Có thể sử dụng phương pháp tiếp cận dựa trên lớp để đọc nhiều trang tính hoặc xem xét tên trang tính bằng cách sử dụng thuộc tính sheet_names .

    Note

    Phương pháp truy cập ExcelFile trước đó đã được chuyển từ pandas. io. trình phân tích cú pháp vào không gian tên cấp cao nhất bắt đầu từ pandas 0. 12. 0.

    Mới trong phiên bản 0. 13

    Hiện có hai cách để đọc trong trang tính từ tệp Excel. Bạn có thể cung cấp chỉ mục của trang tính hoặc tên của trang tính bằng cách chuyển các giá trị khác nhau cho sheet_name .

    • Truyền một chuỗi để chỉ tên của một trang tính cụ thể trong sổ làm việc
    • Truyền một số nguyên để chỉ chỉ mục của một trang tính. Các chỉ số tuân theo quy ước Python, bắt đầu từ 0
    • Giá trị mặc định là sheet_name=0 . Điều này đọc tờ đầu tiên.

    Sử dụng tên trang tính

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    10

    Sử dụng chỉ mục trang tính

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    11

    Sử dụng tất cả các giá trị mặc định

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    12

    Thường xảy ra trường hợp người dùng sẽ chèn các cột để thực hiện các phép tính tạm thời trong Excel và bạn có thể không muốn đọc trong các cột đó. read_excel lấy từ khóa parse_cols để cho phép bạn chỉ định một tập hợp con các cột để phân tích cú pháp

    Nếu parse_cols là một số nguyên, thì nó được coi là cột cuối cùng được phân tích cú pháp

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    13

    Nếu parse_cols là một danh sách các số nguyên, thì nó được coi là chỉ số cột tệp được phân tích cú pháp

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    14

    Note

    Có thể chuyển đổi nội dung của các ô Excel thông qua tùy chọn bộ chuyển đổi. Chẳng hạn, để chuyển đổi một cột thành boolean

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    15

    Tùy chọn này xử lý các giá trị bị thiếu và coi các ngoại lệ trong bộ chuyển đổi là dữ liệu bị thiếu. Các phép biến đổi được áp dụng theo từng ô chứ không phải cho toàn bộ cột, do đó, kiểu mảng không được đảm bảo. Chẳng hạn, một cột gồm các số nguyên có giá trị bị thiếu không thể được chuyển đổi thành một mảng có kiểu số nguyên, vì NaN hoàn toàn là một số float. Bạn có thể che giấu dữ liệu bị thiếu theo cách thủ công để khôi phục số nguyên dtype

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    16

    Để ghi một đối tượng DataFrame vào một trang tính của tệp Excel, bạn có thể sử dụng phương thức phiên bản to_excel . Các đối số phần lớn giống như to_csv được mô tả ở trên, đối số đầu tiên là tên của tệp excel và đối số thứ hai tùy chọn là tên của trang tính . Ví dụ.

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    17

    Tệp có . xls sẽ được viết bằng cách sử dụng xlwt và những phần mở rộng có . xlsx phần mở rộng sẽ được viết bằng cách sử dụng xlsxwriter [nếu có] hoặc openpyxl< . .

    Khung dữ liệu sẽ được viết theo cách cố gắng bắt chước đầu ra REPL. Một sự khác biệt từ 0. 12. 0 là index_label sẽ được đặt ở hàng thứ hai thay vì hàng đầu tiên. Bạn có thể nhận được hành vi trước đó bằng cách đặt tùy chọn merge_cells trong to_excel[] to False:

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    18

    Lớp Bảng điều khiển cũng có phương thức cá thể to_excel , phương thức này ghi mỗi DataFrame trong Bảng điều khiển vào một trang tính riêng biệt.

    Để ghi các DataFrame riêng biệt vào các trang tính riêng biệt trong một tệp Excel, người ta có thể chuyển một ExcelWriter .

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    19

    Note

    Tăng thêm một chút hiệu suất từ ​​ read_excel Bên trong, Excel lưu trữ tất cả dữ liệu số dưới dạng số thực. Bởi vì điều này có thể tạo ra hành vi không mong muốn khi đọc dữ liệu, gấu trúc mặc định cố gắng chuyển đổi số nguyên thành số thực nếu nó không làm mất thông tin [ 1. 0 --> 1 ]. Bạn có thể vượt qua convert_float=False để tắt hành vi này, điều này có thể giúp cải thiện hiệu suất một chút.

    Công cụ soạn thảo Excel¶

    Mới trong phiên bản 0. 13

    pandas chọn trình soạn thảo Excel qua hai phương pháp.

    1. đối số từ khóa công cụ keyword argument
    2. phần mở rộng tên tệp [thông qua mặc định được chỉ định trong tùy chọn cấu hình]

    Theo mặc định, gấu trúc sử dụng XlsxWriter cho . xlsx và openpyxl cho . xlsm và xlwt cho . xls tệp. Nếu bạn đã cài đặt nhiều công cụ, bạn có thể đặt công cụ mặc định thông qua cài đặt tùy chọn cấu hình io. vượt trội. xlsx. nhà vănio. vượt trội. xls. nhà văn . gấu trúc sẽ quay trở lại openpyxl trong . xlsx nếu không có Xlsxwriter.

    Để chỉ định bạn muốn sử dụng trình soạn thảo nào, bạn có thể chuyển đối số từ khóa công cụ tới to_excel và tới ExcelWriter. The built-in engines are:

    • openpyxl . Điều này bao gồm hỗ trợ ổn định cho OpenPyxl 1. 6. 1 đến nhưng không bao gồm 2. 0. 0 và hỗ trợ thử nghiệm cho OpenPyxl 2. 0. 0 trở lên.
    • xlsxwriter
    • xlwt

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    20

    Bảng nhớ tạm¶

    Một cách thuận tiện để lấy dữ liệu là sử dụng phương thức read_clipboard , phương thức này lấy nội dung của bộ đệm khay nhớ tạm và chuyển chúng tới < . Chẳng hạn, bạn có thể sao chép văn bản sau vào khay nhớ tạm [CTRL-C trên nhiều hệ điều hành]. read_table method. For instance, you can copy the following text to the clipboard [CTRL-C on many operating systems]:

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    21

    Và sau đó nhập dữ liệu trực tiếp vào DataFrame bằng cách gọi

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    22

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    23

    Phương thức to_clipboard có thể được sử dụng để ghi nội dung của DataFrame vào khay nhớ tạm. Sau đó, bạn có thể dán nội dung khay nhớ tạm vào các ứng dụng khác [CTRL-V trên nhiều hệ điều hành]. Ở đây chúng tôi minh họa việc ghi một DataFrame vào khay nhớ tạm và đọc lại.

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    24

    Chúng tôi có thể thấy rằng chúng tôi đã lấy lại cùng một nội dung mà chúng tôi đã ghi vào khay nhớ tạm trước đó

    Note

    Bạn có thể cần cài đặt xclip hoặc xsel [với các mô-đun gtk hoặc PyQt4] trên Linux để sử dụng các phương pháp này

    dưa chua¶

    Tất cả các đối tượng pandas đều được trang bị các phương thức to_pickle sử dụng cPickle module to save data structures to disk using the pickle format.

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    25

    Hàm read_pickle trong không gian tên pandas có thể là .

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    26

    Warning

    Tải dữ liệu chọn lọc nhận được từ các nguồn không đáng tin cậy có thể không an toàn

    Nhìn thấy. http. // tài liệu. con trăn. tổ chức/2. 7/thư viện/dưa chua. html

    Warning

    Một số tái cấu trúc nội bộ, 0. 13 [Tái cấu trúc chuỗi] và 0. 15 [Tái cấu trúc chỉ mục], duy trì khả năng tương thích với dưa chua được tạo trước các phiên bản này. Tuy nhiên, chúng phải được đọc bằng pd. read_pickle , thay vì python pickle mặc định. tải . Xem câu hỏi này để được giải thích chi tiết.

    Note

    Những phương pháp này trước đây là pd. lưupd. tải , trước 0. 12. 0 và hiện không được dùng nữa.

    msgpack [thử nghiệm]¶

    Mới trong phiên bản 0. 13. 0

    Bắt đầu bằng 0. 13. 0, pandas đang hỗ trợ định dạng msgpack để tuần tự hóa đối tượng. Đây là một định dạng nhị phân di động nhẹ, tương tự như JSON nhị phân, có hiệu quả về không gian cao và cung cấp hiệu suất tốt cả về ghi [tuần tự hóa] và đọc [giải tuần tự hóa].

    Warning

    Đây là một tính năng rất mới của pandas. Chúng tôi dự định cung cấp một số tối ưu hóa nhất định trong dữ liệu gói thông báo . Vì đây được đánh dấu là THƯ VIỆN THỬ NGHIỆM nên định dạng lưu trữ có thể không ổn định cho đến khi phát hành trong tương lai.

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    27

    Bạn có thể chuyển một danh sách các đối tượng và bạn sẽ nhận lại chúng khi khử lưu huỳnh

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    28

    Bạn có thể vượt qua iterator=True để lặp lại các kết quả đã giải nén

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    29

    Bạn có thể chuyển append=True cho người viết để thêm vào gói hiện có

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    30

    Không giống như các phương thức io khác, to_msgpack khả dụng trên cả cơ sở từng đối tượng, df. to_msgpack[] và sử dụng pd cấp cao nhất. to_msgpack[. ] nơi bạn có thể đóng gói các bộ sưu tập tùy ý gồm danh sách python, dicts, scalar, trong khi trộn lẫn các đối tượng pandas.

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    31

    Đọc/Ghi API¶

    Msgpacks cũng có thể được đọc và ghi vào chuỗi

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    32

    Ngoài ra, bạn có thể nối các chuỗi để tạo danh sách các đối tượng ban đầu

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    33

    HDF5 [PyTables]¶

    HDFStore là một đối tượng giống như dict đọc và ghi pandas bằng định dạng HDF5 hiệu suất cao bằng thư viện PyTables xuất sắc. Xem sách dạy nấu ăn để biết một số chiến lược nâng cao

    Warning

    Kể từ phiên bản 0. 15. 0, pandas requires PyTables >= 3. 0. 0. Các cửa hàng được viết bằng các phiên bản trước của gấu trúc / PyTables >= 2. 3 are fully compatible [this was the previous minimum PyTables required version].

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    34

    Objects can be written to the file just like adding key-value pairs to a dict

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    35

    In a current or later Python session, you can retrieve stored objects

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    36

    Deletion of the object specified by the key

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    37

    Closing a Store, Context Manager

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    38

    Đọc/Ghi API¶

    HDFStore supports an top-level API using read_hdf for reading and to_hdf for writing, similar to how read_csv and to_csv work. [new in 0. 11. 0]

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    39

    Fixed Format¶

    Note

    This was prior to 0. 13. 0 the Storer format.

    The examples above show storing using put , which write the HDF5 to PyTables in a fixed array format, called the fixed format. These types of stores are are not appendable once written [though you can simply remove them and rewrite]. Nor are they queryable; they must be retrieved in their entirety. They also do not support dataframes with non-unique column names. The fixed format stores offer very fast writing and slightly faster reading than table stores. This format is specified by default when using put or to_hdf or by format='fixed' or format='f'

    Warning

    A fixed format will raise a TypeError if you try to retrieve using a where .

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    40

    Table Format¶

    HDFStore supports another PyTables format on disk, the table format. Conceptually a table is shaped very much like a DataFrame, with rows and columns. A table may be appended to in the same or other sessions. In addition, delete & query type operations are supported. This format is specified by format='table' or format='t' to append or put or to_hdf

    Mới trong phiên bản 0. 13

    This format can be set as an option as well pd. set_option['io. hdf. default_format','table'] to enable put/append/to_hdf to by default store in the table format.

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    41

    Note

    You can also create a table by passing format='table' or format='t' to a put operation.

    Hierarchical Keys¶

    Keys to a store can be specified as a string. These can be in a hierarchical path-name like format [e. g. foo/bar/bah ], sẽ tạo hệ thống phân cấp các cửa hàng phụ [hoặc Nhóm in PyTables parlance]. Keys can be specified with out the leading ‘/’ and are ALWAYS absolute [e.g. ‘foo’ refers to ‘/foo’]. Removal operations can remove everything in the sub-store and BELOW, so be careful.

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    42

    Storing Mixed Types in a Table¶

    Storing mixed-dtype data is supported. Strings are stored as a fixed-width using the maximum size of the appended column. Subsequent appends will truncate strings at this length

    Passing min_itemsize={`values`. size} as a parameter to append will set a larger minimum for the string columns. Storing floats, strings, ints, bools, datetime64 are currently supported. For string columns, passing nan_rep = 'nan' to append will change the default nan representation on disk [which converts to/from np. nan], this defaults to nan.

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    43

    Storing Multi-Index DataFrames¶

    Storing multi-index dataframes as tables is very similar to storing/selecting from homogeneous index DataFrames

    In [2]: pd.read_csv['foo.csv']
    Out[2]: 
           date  A  B  C
    0  20090101  a  1  2
    1  20090102  b  3  4
    2  20090103  c  4  5
    
    44

    Querying a Table¶

    Warning

    This query capabilities have changed substantially starting in 0. 13. 0 . Queries from prior version are accepted [with a DeprecationWarning ] printed if its not string-like.

    select and delete operations have an optional criterion that can be specified to select/delete only a subset of the data. This allows one to have a very large on-disk table and retrieve only a portion of the data.

    A query is specified using the Term class under the hood, as a boolean expression.

    • index and columns are supported indexers of a DataFrame
    • major_axis , minor_axis , and items are supported indexers of the Panel
    • if data_columns are specified, these can be used as additional indexers

    Valid comparison operators are

    • =, ==, . =, >, >=, = 1. 7

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      54

      Indexing¶

      You can create/modify an index for a table with create_table_index after data is already in the table [after and append/put operation]. Creating a table index is highly encouraged. This will speed your queries a great deal when you use a select with the indexed dimension as the where .

      Note

      Indexes are automagically created [starting 0. 10. 1 ] on the indexables and any data columns you specify. This behavior can be turned off by passing index=False to append .

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      55

      See here for how to create a completely-sorted-index [CSI] on an existing store

      Query via Data Columns¶

      You can designate [and index] certain columns that you want to be able to perform queries [other than the indexable columns, which you can always query]. For instance say you want to perform this common operation, on-disk, and return just the frame that matches this query. You can specify data_columns = True to force all columns to be data_columns

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      56

      There is some performance degradation by making lots of columns into data columns, so it is up to the user to designate these. In addition, you cannot change data columns [nor indexables] after the first append/put operation [Of course you can simply read in the data and create a new table. ]

      Iterator¶

      Starting in 0. 11. 0 , you can pass, iterator=True or chunksize=number_in_a_chunk to select and select_as_multiple to return an iterator on the results. The default is 50,000 rows returned in a chunk.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      57

      Note

      Mới trong phiên bản 0. 12. 0

      You can also use the iterator with read_hdf which will open, then automatically close the store when finished iterating.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      58

      Note, that the chunksize keyword applies to the source rows. So if you are doing a query, then the chunksize will subdivide the total rows in the table and the query applied, returning an iterator on potentially unequal sized chunks

      Here is a recipe for generating a query and using it to create equal sized return chunks

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      59

      Advanced Queries¶

      Select a Single Column

      To retrieve a single indexable or data column, use the method select_column . This will, for example, enable you to get the index very quickly. These return a Series of the result, indexed by the row number. These do not currently accept the where selector.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      60

      Selecting coordinates

      Sometimes you want to get the coordinates [a. k. a the index locations] of your query. This returns an Int64Index of the resulting locations. Các tọa độ này cũng có thể được chuyển đến các thao tác where tiếp theo.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      61

      Selecting using a where mask

      Sometime your query can involve creating a list of rows to select. Usually this mask would be a resulting index from an indexing operation. This example selects the months of a datetimeindex which are 5.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      62

      Storer Object

      If you want to inspect the stored object, retrieve via get_storer . You could use this programmatically to say get the number of rows in an object.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      63

      Multiple Table Queries¶

      Mới trong 0. 10. 1 are the methods append_to_multiple and select_as_multiple , that can perform appending/selecting from multiple tables at once. Ý tưởng là có một bảng [gọi nó là bảng chọn] mà bạn lập chỉ mục cho hầu hết/tất cả các cột và thực hiện các truy vấn của mình. The other table[s] are data tables with an index matching the selector table’s index. You can then perform a very fast query on the selector table, yet get lots of data back. This method is similar to having a very wide table, but enables more efficient queries.

      The append_to_multiple method splits a given single DataFrame into multiple tables according to d , a dictionary that maps the table names to a list of ‘columns’ you want in that table. If None is used in place of a list, that table will have the remaining unspecified columns of the given DataFrame. The argument selector defines which table is the selector table [which you can make queries from]. The argument dropna will drop rows from the input DataFrame to ensure tables are synchronized. This means that if a row for one of the tables being written to is entirely np. NaN , that row will be dropped from all tables.

      If dropna is False, THE USER IS RESPONSIBLE FOR SYNCHRONIZING THE TABLES. Remember that entirely np. Nan rows are not written to the HDFStore, so if you choose to call dropna=False , some tables may have more rows than others, and therefore select_as_multiple may not work or it may return unexpected results.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      64

      Delete from a Table¶

      You can delete from a table selectively by specifying a where . In deleting rows, it is important to understand the PyTables deletes rows by erasing the rows, then moving the following data. Thus deleting can potentially be a very expensive operation depending on the orientation of your data. This is especially true in higher dimensional objects [ Panel and Panel4D ]. To get optimal performance, it’s worthwhile to have the dimension you are deleting be the first of the indexables .

      Data is ordered [on the disk] in terms of the indexables . Here’s a simple use case. You store panel-type data, with dates in the major_axis and ids in the minor_axis . The data is then interleaved like this.

      • date_1
        • id_1
        • id_2
        • .
        • id_n
      • date_2
        • id_1
        • .
        • id_n

      It should be clear that a delete operation on the major_axis will be fairly quick, as one chunk is removed, then the following data moved. On the other hand a delete operation on the minor_axis will be very expensive. In this case it would almost certainly be faster to rewrite the table using a where that selects all but the missing data.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      65

      Xin lưu ý rằng HDF5 KHÔNG TỰ ĐỘNG ĐẶT LẠI KHÔNG GIAN trong các tệp h5. Thus, repeatedly deleting [or removing nodes] and adding again WILL TEND TO INCREASE THE FILE SIZE. To clean the file, use ptrepack [see below].

      Compression¶

      PyTables allows the stored data to be compressed. This applies to all kinds of stores, not just tables.

      • Pass complevel=int for a compression level [1-9, with 0 being no compression, and the default]
      • Pass complib=lib where lib is any of zlib, bzip2, lzo, blosc for whichever compression library you prefer.

      HDFStore will use the file based compression scheme if no overriding complib or complevel options are provided. blosc offers very fast compression, and is my most used. Note that lzo and bzip2 may not be installed [by Python] by default.

      Compression for all objects within the file

      • store_compressed = HDFStore['store_compressed. h5', complevel=9, complib='blosc']

      Or on-the-fly compression [this only applies to tables]. You can turn off file compression for a specific table by passing complevel=0

      • store. append['df', df, complib='zlib', complevel=5]

      ptrepack

      PyTables offers better write performance when tables are compressed after they are written, as opposed to turning on compression at the very beginning. You can use the supplied PyTables utility ptrepack . In addition, ptrepack can change compression levels after the fact.

      • ptrepack --chunkshape=auto --propindexes --complevel=9 --complib=blosc in. h5 out. h5

      Furthermore ptrepack in. h5 out. h5 will repack the file to allow you to reuse previously deleted space. Alternatively, one can simply remove the file and write again, or use the copy method.

      Notes & Caveats¶

      • Once a table is created its items [Panel] / columns [DataFrame] are fixed; only exactly the same columns can be appended
      • If a row has np. nan for EVERY COLUMN [having a nan in a string, or a NaT in a datetime-like column counts as having a value], then those rows WILL BE DROPPED IMPLICITLY. This limitation may be addressed in the future.
      • HDFStore is not-threadsafe for writing. The underlying PyTables only supports concurrent reads [via threading or processes]. If you need reading and writing at the same time, you need to serialize these operations in a single thread in a single process. You will corrupt your data otherwise. See the issue [. 2397] for more information.
      • If you use locks to manage write access between multiple processes, you may want to use fsync[] before releasing write locks. For convenience you can use store. flush[fsync=True] to do this for you.
      • PyTables only supports fixed-width string columns in tables . The sizes of a string based indexing column [e. g. columns or minor_axis] are determined as the maximum size of the elements in that axis or by passing the parameter
      • Be aware that timezones [e. g. , pytz. timezone['US/Eastern'] ] không nhất thiết phải bằng nhau giữa các phiên bản múi giờ. So if data is localized to a specific timezone in the HDFStore using one version of a timezone library and that data is updated with another version, the data will be converted to UTC since these timezones are not considered equal. Either use the same version of timezone library or use tz_convert with the updated timezone definition.

      Warning

      PyTables will show a NaturalNameWarning if a column name cannot be used as an attribute selector. Generally identifiers that have spaces, start with numbers, or _ , or have - embedded are not considered natural. These types of identifiers cannot be used in a where clause and are generally a bad idea.

      DataTypes¶

      HDFStore will map an object dtype to the PyTables underlying dtype. This means the following types are known to work.

      • trôi nổi. float64, float32, float16 [using np. nan to represent invalid values]
      • integer . int64, int32, int8, uint64, uint32, uint8
      • bool
      • datetime64[ns] [using NaT to represent invalid values]
      • object . strings [using np. nan để biểu thị các giá trị không hợp lệ]

      Hiện tại, các cột unicodedatetime [được biểu thị bằng . In addition, even though a column may look like a object], WILL FAIL. In addition, even though a column may look like a datetime64[ns] , if it contains np. nan , this WILL FAIL. You can try to convert datetimelike columns to proper datetime64[ns] columns, that possibly contain NaT to represent invalid values. [Some of these issues have been addressed and these conversion may not be necessary in future versions of pandas]

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      66

      Categorical Data¶

      New in version 0. 15. 2

      Writing data to a HDFStore that contains a category dtype was implemented in 0. 15. 2. Queries work the same as if it was an object array. However, the category dtyped data is stored in a more efficient manner.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      67

      Warning

      The format of the Categorical is readable by prior versions of pandas [< 0. 15. 2], but will retrieve the data as an integer based column [e. g. the codes ]. However, the categories can be retrieved but require the user to select them manually using the explicit meta path.

      The data is stored like so

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      68

      String Columns¶

      min_itemsize

      The underlying implementation of HDFStore uses a fixed column width [itemsize] for string columns. A string column itemsize is calculated as the maximum of the length of data [for that column] that is passed to the HDFStore , in the first append. Subsequent appends, may introduce a string for a column larger than the column can hold, an Exception will be raised [otherwise you could have a silent truncation of these columns, leading to loss of information]. In the future we may relax this and allow a user-specified truncation to occur.

      Pass min_itemsize on the first table creation to a-priori specify the minimum length of a particular string column. min_itemsize can be an integer, or a dict mapping a column name to an integer. You can pass values as a key to allow all indexables or data_columns to have this min_itemsize.

      Starting in 0. 11. 0, passing a min_itemsize dict will cause all passed columns to be created as data_columns automatically.

      Note

      If you are not passing any data_columns, then the min_itemsize will be the maximum of the length of any string passed

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      69

      nan_rep

      String columns will serialize a np. nan [a missing value] with the nan_rep string representation. This defaults to the string value nan . You could inadvertently turn an actual nan value into a missing value.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      70

      External Compatibility¶

      HDFStore write table format objects in specific formats suitable for producing loss-less round trips to pandas objects. For external compatibility, HDFStore can read native PyTables format tables. It is possible to write an HDFStore object that can easily be imported into R using the rhdf5 library. Create a table format store like this.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      71

      Backwards Compatibility¶

      0. 10. 1 of HDFStore can read tables created in a prior version of pandas, however query terms using the prior [undocumented] methodology are unsupported. HDFStore will issue a warning if you try to use a legacy-format file. You must read in the entire file and write it out using the new format, using the method copy to take advantage of the updates. The group attribute pandas_version contains the version information. copy takes a number of options, please see the docstring.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      72

      Performance¶

      • Tables come with a writing performance penalty as compared to regular stores. The benefit is the ability to append/delete and query [potentially very large amounts of data]. Write times are generally longer as compared with regular stores. Query times can be quite fast, especially on an indexed axis.
      • You can pass chunksize= to append , specifying the write chunksize [default is 50000]. This will significantly lower your memory usage on writing.
      • You can pass expectedrows= to the first append , to set the TOTAL number of expected rows that PyTables will expected. This will optimize read/write performance.
      • Duplicate rows can be written to tables, but are filtered out in selection [with the last items being selected; thus a table is unique on major, minor pairs]
      • A PerformanceWarning will be raised if you are attempting to store types that will be pickled by PyTables [rather than stored as endemic types]. See Here for more information and some solutions.

      Experimental¶

      HDFStore supports Panel4D storage.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      73

      These, by default, index the three axes items, major_axis, minor_axis . On an AppendableTable it is possible to setup with the first append a different indexing scheme, depending on how you want to store your data. Pass the axes keyword with a list of dimensions [currently must by exactly 1 less than the total dimensions of the object]. This cannot be changed after table creation.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      74

      SQL Queries¶

      The pandas. io. sql module provides a collection of query wrappers to both facilitate data retrieval and to reduce dependency on DB-specific API. Database abstraction is provided by SQLAlchemy if installed, in addition you will need a driver library for your database.

      New in version 0. 14. 0

      If SQLAlchemy is not installed, a fallback is only provided for sqlite [and for mysql for backwards compatibility, but this is deprecated and will be removed in a future version]. This mode requires a Python database adapter which respect the Python DB-API

      See also some cookbook examples for some advanced strategies

      The key functions are

      read_sql_table [table_name, con[, schema, . ]]Read SQL database table into a DataFrame. read_sql_query [sql, con[, index_col, . ]]Read SQL query into a DataFrame. read_sql [sql, con[, index_col, . ]]Read SQL query or database table into a DataFrame. DataFrame. to_sql [name, con[, flavor, . ]]Write records stored in a DataFrame to a SQL database.

      Note

      The function read_sql[] is a convenience wrapper around read_sql_table[] and read_sql_query[] [and for backward compatibility] and will delegate to specific function depending on the provided input [database table name or sql query].

      In the following example, we use the SQlite SQL database engine. You can use a temporary SQLite database where data are stored in “memory”

      To connect with SQLAlchemy you use the create_engine[] function to create an engine object from database URI. You only need to create the engine once per database you are connecting to. For more information on create_engine[] and the URI formatting, see the examples below and the SQLAlchemy documentation

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      75

      Viết DataFrames¶

      Assuming the following data is in a DataFrame data , we can insert it into the database using to_sql[] .

      idDateCol_1Col_2Col_3262012-10-18X25. 7True422012-10-19Y-12. 4False632012-10-20Z5. 73True

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      76

      With some databases, writing large DataFrames can result in errors due to packet size limitations being exceeded. This can be avoided by setting the chunksize parameter when calling to_sql . For example, the following writes data to the database in batches of 1000 rows at a time.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      77

      SQL data types¶

      to_sql[] will try to map your data to an appropriate SQL data type based on the dtype of the data. When you have columns of dtype object , pandas will try to infer the data type.

      You can always override the default type by specifying the desired SQL type of any of the columns by using the dtype argument. This argument needs a dictionary mapping column names to SQLAlchemy types [or strings for the sqlite3 fallback mode]. For example, specifying to use the sqlalchemy String type instead of the default Text type for string columns.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      78

      Note

      Due to the limited support for timedelta’s in the different database flavors, columns with type timedelta64 will be written as integer values as nanoseconds to the database and a warning will be raised.

      Note

      Columns of category dtype will be converted to the dense representation as you would get with np. asarray[categorical] [e. g. for string categories this gives an array of strings]. Because of this, reading the database table back in does not generate a categorical.

      Reading Tables¶

      read_sql_table[] will read a database table given the table name and optionally a subset of columns to read.

      Note

      In order to use read_sql_table[] , you must have the SQLAlchemy optional dependency installed.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      79

      You can also specify the name of the column as the DataFrame index, and specify a subset of columns to be read

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      80

      And you can explicitly force columns to be parsed as dates

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      81

      If needed you can explicitly specify a format string, or a dict of arguments to pass to pandas. to_datetime[] .

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      82

      You can check if a table exists using has_table[]

      Schema support¶

      New in version 0. 15. 0

      Reading from and writing to different schema’s is supported through the schema keyword in the read_sql_table[] and to_sql[] functions. Note however that this depends on the database flavor [sqlite does not have schema’s]. For example.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      83

      Querying¶

      You can query using raw SQL in the read_sql_query[] function. In this case you must use the SQL variant appropriate for your database. When using SQLAlchemy, you can also pass SQLAlchemy Expression language constructs, which are database-agnostic.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      84

      Of course, you can specify a more “complex” query

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      85

      The read_sql_query[] function supports a chunksize argument. Specifying this will return an iterator through chunks of the query result.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      86

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      87

      You can also run a plain query without creating a dataframe with execute[] . This is useful for queries that don’t return values, such as INSERT. This is functionally equivalent to calling execute on the SQLAlchemy engine or db connection object. Again, you must use the SQL syntax variant appropriate for your database.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      88

      Engine connection examples¶

      To connect with SQLAlchemy you use the create_engine[] function to create an engine object from database URI. You only need to create the engine once per database you are connecting to.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      89

      For more information see the examples the SQLAlchemy documentation

      Sqlite fallback¶

      The use of sqlite is supported without using SQLAlchemy. This mode requires a Python database adapter which respect the Python DB-API

      You can create connections like so

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      90

      And then issue the following queries

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      91

      Google BigQuery [Experimental]¶

      Mới trong phiên bản 0. 13. 0

      The pandas. io. gbq module provides a wrapper for Google’s BigQuery analytics web service to simplify retrieving results from BigQuery tables using SQL-like queries. Result sets are parsed into a pandas DataFrame with a shape and data types derived from the source table. Additionally, DataFrames can be appended to existing BigQuery tables if the destination table is the same shape as the DataFrame.

      For specifics on the service itself, see here

      As an example, suppose you want to load all data from an existing BigQuery table . test_dataset. test_table into a DataFrame using the read_gbq[] function.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      92

      You will then be authenticated to the specified BigQuery account via Google’s Oauth2 mechanism. In general, this is as simple as following the prompts in a browser window which will be opened for you. Should the browser not be available, or fail to launch, a code will be provided to complete the process manually. Additional information on the authentication mechanism can be found here

      You can define which column from BigQuery to use as an index in the destination DataFrame as well as a preferred column order as follows

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      93

      Finally, you can append data to a BigQuery table from a pandas DataFrame using the to_gbq[] function. This function uses the Google streaming API which requires that your destination table exists in BigQuery. Given the BigQuery table already exists, your DataFrame should match the destination table in column order, structure, and data types. DataFrame indexes are not supported. By default, rows are streamed to BigQuery in chunks of 10,000 rows, but you can pass other chuck values via the chunksize argument. You can also see the progess of your post via the verbose flag which defaults to True . The http response code of Google BigQuery can be successful [200] even if the append failed. For this reason, if there is a failure to append to the table, the complete error response from BigQuery is returned which can be quite long given it provides a status for each row. Bạn có thể muốn bắt đầu với các khối nhỏ hơn để kiểm tra xem kích thước và loại khung dữ liệu của bạn có khớp với bảng đích của bạn không để giúp gỡ lỗi đơn giản hơn.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      94

      The BigQuery SQL query language has some oddities, see here

      While BigQuery uses SQL-like syntax, it has some important differences from traditional databases both in functionality, API limitations [size and quantity of queries or uploads], and how Google charges for use of the service. You should refer to Google documentation often as the service seems to be changing and evolving. BigQuery là cách tốt nhất để phân tích nhanh chóng các tập dữ liệu lớn, nhưng nó không phải là sự thay thế trực tiếp cho cơ sở dữ liệu giao dịch

      You can access the management console to determine project id’s by:

      As of 0. 15. 2, the gbq module has a function generate_bq_schema which will produce the dictionary representation of the schema.

      In [2]: pd.read_csv['foo.csv']
      Out[2]: 
             date  A  B  C
      0  20090101  a  1  2
      1  20090102  b  3  4
      2  20090103  c  4  5
      
      95

      Warning

      To use this module, you will need a valid BigQuery account. See for details on the service

      How to create tables in Python?

      Creating a table using python .
      Establish connection with a database using the connect[] method
      Create a cursor object by invoking the cursor[] method on the above created connection object
      Now execute the CREATE TABLE statement using the execute[] method of the Cursor class

      How to create txt files in Python?

      #creating a text file with the command function "w" f = open["myfile. txt", "w"] #This "w" command can also be used create a new file but unlike the the "x" command the "w" command will overwrite any existing file found with the same file name.

      How to convert text file to HTML table in Python?

      Add a library reference [import the library] to your Python project. Open the source TXT file in Python. Call the 'save[]' method, passing an output filename with HTML extension. Get the result of TXT conversion as HTML

      How to extract data from text file to excel using Python?

      Your answer .
      Step 1. Install the Pandas package. If you haven't already done so, install the Pandas package
      Step 2. Capture the path where your text file is stored
      Step 3. Specify the path where the new CSV file will be saved
      Step 4. Chuyển đổi tệp văn bản thành CSV bằng Python

    Chủ Đề