Pandas学习笔记(一)

"Pandas学习笔记"

Posted by jhljx on November 20, 2017

目录

1. Pandas读取CSV
2. Pandas写入CSV

Pandas读取CSV文件

pd.read_csv(filepath_or_buffer, sep=’,’, delimiter=None, header=’infer’, names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression=’infer’, thousands=None, decimal=b’.’, lineterminator=None, quotechar=’”’, quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=False, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, skip_footer=0, doublequote=True, delim_whitespace=False, as_recarray=False, compact_ints=False, use_unsigned=False, low_memory=True, buffer_lines=None, memory_map=False, float_precision=None)

  • filepath_or_buffer : str, pathlib.Path, py._path.local.LocalPath or any object with a read()
    method (such as a file handle or 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.csv
  • sep : str, default ‘,’
    Delimiter to use. If sep is None, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detect the separator by Python’s builtin sniffer tool, csv.Sniffer. In addition, separators longer than 1 character and different from ‘\s+’ will be interpreted as regular expressions and will also force the use of the Python parsing engine. Note that regex delimiters are prone to ignoring quoted data. Regex example: ‘\r\t’
  • delimiter : str, default None
    Alternative argument name for sep.
  • delim_whitespace : boolean, default False
    Specifies whether or not whitespace (e.g. ‘ ‘ or ‘ ‘) will be used as the sep. Equivalent to setting sep=’\s+’. If this option is set to True, nothing should be passed in for the delimiter parameter.
    New in version 0.18.1: support for the Python parser.
  • 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 to infer the column names: if no names are passed the behavior is identical to header=0 and column names are inferred from the first line of the file, if column names are passed explicitly then the behavior is identical to header=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.
  • names : array-like, default None
    List of column names to use. If file contains no header row, then you should explicitly pass header=None. Duplicates in this list will cause a UserWarning to be issued.
  • index_col : int or sequence or False, default None
    Column to use as the row labels of the DataFrame. If a sequence is given, a MultiIndex is used. If you have a malformed file with delimiters at the end of each line, you might consider index_col=False to force pandas to not use the first column as the index (row names)
  • usecols : array-like or callable, default None
    Return a subset of the columns. If array-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in names or inferred from the document header row(s). For example, a valid array-like usecols parameter would be [0, 1, 2] or [‘foo’, ‘bar’, ‘baz’].
    If callable, the callable function will be evaluated against the column names, returning names where the callable function evaluates to True. An example of a valid callable argument would be lambda x: x.upper() in [‘AAA’, ‘BBB’, ‘DDD’]. Using this parameter results in much faster parsing time and lower memory usage.
  • as_recarray : boolean, default False
    Deprecated since version 0.19.0: Please call pd.read_csv(…).to_records() instead.
    Return a NumPy recarray instead of a DataFrame after parsing the data. If set to True, this option takes precedence over the squeeze parameter. In addition, as row indices are not available in such a format, the index_col parameter will be ignored.
  • squeeze : boolean, default False
    If the parsed data only contains one column then return a Series
  • prefix : str, default None
    Prefix to add to column numbers when no header, e.g. ‘X’ for X0, X1, …
  • mangle_dupe_cols : boolean, default True
    Duplicate columns will be specified as ‘X.0’…’X.N’, rather than ‘X’…’X’. Passing in False will cause data to be overwritten if there are duplicate names in the columns.
  • dtype : Type name or dict of column -> type, default None
    Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32} Use str or object to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion.
  • engine : {‘c’, ‘python’}, optional
    Parser engine to use. The C engine is faster while the python engine is currently more feature-complete.
  • converters : dict, default None
    Dict of functions for converting values in certain columns. Keys can either be integers or column labels
  • true_values : list, default None
    Values to consider as True
  • false_values : list, default None
    Values to consider as False
  • skipinitialspace : boolean, default False
    Skip spaces after delimiter.
  • skiprows : list-like or integer or callable, default None
    Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file.
    If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be lambda x: x in [0, 2].
  • skipfooter : int, default 0
    Number of lines at bottom of file to skip (Unsupported with engine=’c’)
  • skip_footer : int, default 0
    Deprecated since version 0.19.0: Use the skipfooter parameter instead, as they are identical
  • nrows : int, default None
    Number of rows of file to read. Useful for reading pieces of large files
  • na_values : scalar, str, list-like, or dict, default None
    Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: ‘’, ‘#N/A’, ‘#N/A N/A’, ‘#NA’, ‘-1.#IND’, ‘-1.#QNAN’, ‘-NaN’, ‘-nan’, ‘1.#IND’, ‘1.#QNAN’, ‘N/A’, ‘NA’, ‘NULL’, ‘NaN’, ‘n/a’, ‘nan’, ‘null’.
  • keep_default_na : bool, default True
    If na_values are specified and keep_default_na is False the default NaN values are overridden, otherwise they’re appended to.
  • na_filter : boolean, default True
    Detect missing value markers (empty strings and the value of na_values). In data without any NAs, passing na_filter=False can improve the performance of reading a large file
  • verbose : boolean, default False
    Indicate number of NA values placed in non-numeric columns
  • skip_blank_lines : boolean, default True
    If True, skip over blank lines rather than interpreting as NaN values
  • parse_dates : boolean or list of ints or names or list of lists or dict, default False
    • boolean. If True -> try parsing the index.
    • list of ints or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.
    • list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column.
    • dict, e.g. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’
      If a column or index contains an unparseable date, the entire column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use pd.to_datetime after pd.read_csv
      Note: A fast-path exists for iso8601-formatted dates.
  • infer_datetime_format : boolean, default False
    If True and parse_dates is enabled, pandas will attempt to infer the format of the datetime strings in the columns, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by 5-10x.
  • keep_date_col : boolean, default False
    If True and parse_dates specifies combining multiple columns then keep the original columns.
  • date_parser : function, default None
    Function to use for converting a sequence of string columns to an array of datetime instances. The default uses dateutil.parser.parser to do the conversion. Pandas will try to call date_parser in three different ways, advancing to the next if an exception occurs: 1) Pass one or more arrays (as defined by parse_dates) as arguments; 2) concatenate (row-wise) the string values from the columns defined by parse_dates into a single array and pass that; and 3) call date_parser once for each row using one or more strings (corresponding to the columns defined by parse_dates) as arguments.
  • dayfirst : boolean, default False
    DD/MM format dates, international and European format
  • iterator : boolean, default False
    Return TextFileReader object for iteration or getting chunks with get_chunk().
  • chunksize : int, default None
    Return TextFileReader object for iteration. See the IO Tools docs for more information on iterator and chunksize.
  • compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’
    For on-the-fly decompression of on-disk data. If ‘infer’ and filepath_or_buffer is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, or ‘.xz’ (otherwise no decompression). If using ‘zip’, the ZIP file must contain only one data file to be read in. Set to None for no decompression.
    New in version 0.18.1: support for ‘zip’ and ‘xz’ compression.
  • thousands : str, default None
    Thousands separator
  • decimal : str, default ‘.’
    Character to recognize as decimal point (e.g. use ‘,’ for European data).
  • float_precision : string, default None
    Specifies which converter the C engine should use for floating-point values. The options are None for the ordinary converter, high for the high-precision converter, and round_trip for the round-trip converter.
  • lineterminator : str (length 1), default None
    Character to break file into lines. Only valid with C parser.
  • quotechar : str (length 1), optional
    The character used to denote the start and end of a quoted item. Quoted items can include the delimiter and it will be ignored.
  • quoting : int or csv.QUOTE_* instance, default 0
    Control field quoting behavior per csv.QUOTE_* constants. Use one of QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).
  • doublequote : boolean, default True
    When quotechar is specified and quoting is not QUOTE_NONE, indicate whether or not to interpret two consecutive quotechar elements INSIDE a field as a single quotechar element.
  • escapechar : str (length 1), default None
    One-character string used to escape delimiter when quoting is QUOTE_NONE.
  • comment : str, default None
    Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as skip_blank_lines=True), fully commented lines are ignored by the parameter header but not by skiprows. For example, if comment=’#’, parsing ‘#emptyna,b,cn1,2,3’ with header=0 will result in ‘a,b,c’ being treated as the header.
  • encoding : str, default None
    Encoding to use for UTF when reading/writing (ex. ‘utf-8’). List of Python standard encodings
  • dialect : str or csv.Dialect instance, default None
    If provided, this parameter will override values (default or not) for the following parameters: delimiter, doublequote, escapechar, skipinitialspace, quotechar, and quoting. If it is necessary to override values, a ParserWarning will be issued. See csv.Dialect documentation for more details.
  • tupleize_cols : boolean, default False
    Deprecated since version 0.21.0: This argument will be removed and will always convert to MultiIndex
    Leave a list of tuples on columns as is (default is to convert to a MultiIndex on the columns)
  • error_bad_lines : boolean, default True
    Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these “bad lines” will dropped from the DataFrame that is returned.
  • warn_bad_lines : boolean, default True
    If error_bad_lines is False, and warn_bad_lines is True, a warning for each “bad line” will be output.
  • low_memory : boolean, default True
    Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set False, or specify the type with the dtype parameter. Note that the entire file is read into a single DataFrame regardless, use the chunksize or iterator parameter to return the data in chunks. (Only valid with C parser)
  • buffer_lines : int, default None
    Deprecated since version 0.19.0: This argument is not respected by the parser
  • compact_ints : boolean, default False
    Deprecated since version 0.19.0: Argument moved to pd.to_numeric
    If compact_ints is True, then for any column that is of integer dtype, the parser will attempt to cast it as the smallest integer dtype possible, either signed or unsigned depending on the specification from the use_unsigned parameter.
  • use_unsigned : boolean, default False
    Deprecated since version 0.19.0: Argument moved to pd.to_numeric
    If integer columns are being compacted (i.e. compact_ints=True), specify whether the column should be compacted to the smallest signed or unsigned integer dtype.
  • memory_map : boolean, default False
    If a filepath is provided for filepath_or_buffer, map the file object directly onto memory and access the data directly from there. Using this option can improve performance because there is no longer any I/O overhead.

Returns: result: DataFrame or TextParser

  • 必填参数
    • filepath_or_buffer : str,pathlib。str, pathlib.Path, py._path.local.LocalPath or any object with a read() method (such as a file handle or StringIO)
      读取文件路径,可以是URL,可用URL类型包括:http, ftp, s3和文件。
  • 常用参数1

    • sep: str, default ‘,’
      指定分隔符。如果不指定参数,则会尝试使用逗号分隔。csv文件一般为逗号分隔符。
    • delimiter: str, default None
      定界符,备选分隔符(如果指定该参数,则sep参数失效)
    • delim_whitespace: boolean, default False.
      指定空格(例如’ ‘或者’ ‘)是否作为分隔符使用,等效于设定sep='\s+'
      如果这个参数设定为Ture那么delimiter 参数失效。
  • 常用参数2,对于数据读取有表头和没表头的情况很实用

    • header: int or list of ints, default ‘infer’
      指定行数用来作为列名,数据开始行数。如果文件中没有列名,则默认为0,否则设置为None。
  • 常用参数3

    • names: array-like, default None
      用于结果的列名列表,对各列重命名,即添加表头。
      如数据有表头,但想用新的表头,可以设置header=0,names=['a','b']实现表头定制。
    • index_col : int or sequence or False, default None
      用作行索引的列编号或者列名,如果给定一个序列则有多个行索引。
      可使用index_col=[0,1]来指定文件中的第1和2列为索引列。
  • 常用参数4

    • usecols: array-like, default None
      返回一个数据子集,即选取某几列,不读取整个文件的内容,有助于加快速度和降低内存。 usecols=[1,2]usercols=['a','b']
    • squeeze: boolean, default False
      如果文件只包含一列,则返回一个Series
    • prefix: str, default None
      在没有列标题时,给列添加前缀。例如:添加‘X’ 成为 X0, X1, …
    • mangle_dupe_cols: boolean, default True
      重复的列,将‘X’…’X’表示为‘X.0’…’X.N’。如果设定为False则会将所有重名列覆盖。
  • 不常用参数

    • dtype: Type name or dict of column -> type, default None
      每列数据的数据类型。例如 {‘a’: np.float64, ‘b’: np.int32}
    • engine: {‘c’, ‘python’}, optional
      使用的分析引擎。可以选择C或者是python。C引擎快但是Python引擎功能更加完备。
    • converters: dict, default None
      列转换函数的字典。key可以是列名或者列的序号。
    • true_values和false_values: list, default None
      Values to consider as True or False
    • skipinitialspace: boolean, default False
      忽略分隔符后的空白(默认为False,即不忽略)
    • skiprows: list-like or integer, default None
      需要忽略的行数(从文件开始处算起),或需要跳过的行号列表(从0开始)。
    • skipfooter: int, default 0
      从文件尾部开始忽略。 (c引擎不支持)
    • nrows: int, default None
      需要读取的行数(从文件头开始算起)。
    • na_values: scalar, str, list-like, or dict, default None
      一组用于替换NA/NaN的值。如果传参,需要制定特定列的空值。
      默认为‘1.#IND’, ‘1.#QNAN’, ‘N/A’, ‘NA’, ‘NULL’, ‘NaN’, ‘nan’。
    • keep_default_na: bool, default True
      如果指定na_values参数,并且keep_default_na=False,那么默认的NaN将被覆盖,否则添加。
    • na_filter: boolean, default True
      是否检查丢失值(空字符串或者是空值)。
      对于大文件来说数据集中没有空值,设定na_filter=False可以提升读取速度。
    • verbose: boolean, default False
      是否打印各种解析器的输出信息,例如:“非数值列中缺失值的数量”等。
    • skip_blank_lines: boolean, default True
      如果为True,则跳过空行;否则记为NaN。
  • 用于指定日期类型的参数

    • parse_dates: boolean or list of ints or names or list of lists or dict, default False
      boolean. True -> 解析索引
      list of ints or names. e.g. If [1, 2, 3] -> 解析1,2,3列的值作为独立的日期列;
      list of lists. e.g. If [[1, 3]] -> 合并1,3列作为一个日期列使用
      dict, e.g. {‘foo’ : [1, 3]} -> 将1,3列合并,并给合并后的列起名为”foo”
      示例:df=pd.read_csv(file_path,parse_dates=[‘time1’,’time2’]),
      把time1和time2两列解析为日期格式。
      这里不得不说,很遗憾中文不行,比如‘4月5日’这种格式就不能解析。
    • infer_datetime_format: boolean, default False
      如果设定为True并且parse_dates 可用,那么pandas将尝试转换为日期类型,如果可以转换,转换方法并解析。 在某些情况下会快5~10倍。
    • keep_date_col: boolean, default False
      如果连接多列解析日期,则保持参与连接的列。默认为False。
    • date_parser: function, default None
      于解析日期的函数,默认使用dateutil.parser.parser来做转换。
      Pandas尝试使用三种不同的方式解析,如果遇到问题则使用下一种方式。
      1.使用一个或者多个arrays(由parse_dates指定)作为参数;
      2.连接指定多列字符串作为一个列作为参数;
      3.每行调用一次date_parser函数来解析一个或者多个字符串(由parse_dates指定)作为参数。
    • dayfirst: boolean, default False
      DD/MM格式的日期类型
  • 大文件参数

    • iterator: boolean, default False
      返回一个TextFileReader 对象,以便逐块处理文件。
    • chunksize: int, default None
      文件块的大小, See IO Tools docs for more informationon iterator and chunksize.
    • compression: {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’
      直接使用磁盘上的压缩文件。如果使用infer参数,则使用 gzip, bz2, zip或者解压文件名中以’.gz’,’.bz2’, ‘.zip’, or ‘xz’这些为后缀的文件,否则不解压。如果使用zip,那么ZIP包中必须只包含一个文件。设置为 None则不解压。新版本0.18.1版本支持zip和xz解压。
    • thousands: str, default None
      千分位分割符,如“,”或者“.”
    • decimal: str, default ‘.’
      字符中的小数点 (例如:欧洲数据使用‘,’).
    • float_precision: string, default None
      Specifies which converter the C engine should use for floating-point values.
      The options are None for the ordinary converter, high for the high-precision converter, and round_trip for the round-trip converter.
    • lineterminator : str (length 1), default None
      行分割符,只在C解析器下使用。
    • quotechar: str (length 1), optional
      引号,用作标识开始和解释的字符,引号内的分割符将被忽略。
    • quoting: int or csv.QUOTE_* instance, default 0
      控制csv中的引号常量。
      可选 QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3)
    • doublequote: boolean, default True
      双引号,当单引号已经被定义,并且quoting 参数不是QUOTE_NONE的时候,使用双引号表示引号内的元素作为一 个元素使用。
    • escapechar: str (length 1), default None
      当quoting 为QUOTE_NONE时,指定一个字符使的不受分隔符限值。
    • comment: str, default None
      标识着多余的行不被解析。如果该字符出现在行首,这一行将被全部忽略。
      这个参数只能是一个字符,空行(就像skip_blank_lines=True)注释行被header和skiprows忽略一样。例如 如果指定comment=’#’解析’#empty\na,b,c\n1,2,3’以header=0 那么返回结果将是以’a,b,c’作为header。
  • 其他参数

    • encoding: str, default None
      指定字符集类型,通常指定为’utf-8’。List of Python standard encodings
    • dialect: str or csv.Dialect instance, default None
      如果没有指定特定的语言,如果sep大于一个字符则忽略。具体查看csv.Dialect 文档
    • tupleize_cols: boolean, default False
      Leave a list of tuples on columns as is (default is to convert to a Multi Index on the columns)
    • error_bad_lines: boolean, default True
      如果一行包含太多的列,那么默认不会返回DataFrame ,如果设置成false,那么会将改行剔除(只能在C解析器下使用)。
    • warn_bad_lines: boolean, default True
      如果error_bad_lines =False,并且warn_bad_lines =True 那么所有的“bad lines”将会被输出(只能在C解析器下使用)。
    • low_memory: boolean, default True
      分块加载到内存,在低内存消耗中解析。但是可能出现类型混淆。
      确保类型不被混淆需要设置为False。或者使用dtype 参数指定类型。
      注意使用chunksize 或者iterator 参数分块读入会将整个文件读入到一个Dataframe,而忽略类型(只能在C解析器中有效)

Pandas输出CSV文件

DataFrame.to_csv(path_or_buf=None, sep=’, ‘, na_rep=’’, float_format=None, columns=None, header=True, index=True, index_label=None, mode=’w’, encoding=None, compression=None, quoting=None, quotechar=’”’, line_terminator=’\n’, chunksize=None, tupleize_cols=None, date_format=None, doublequote=True, escapechar=None, decimal=’.’)

Parameter:

  • path_or_buf : string or file handle, default None
    File path or object, if None is provided the result is returned as a string.
  • sep : character, default ‘,’
    Field delimiter for the output file.
  • na_rep : string, default ‘’
    Missing data representation
  • columns : sequence, optional
    Columns to write
  • header : boolean or list of string, default True
    Write out the column names. If a list of strings is given it is assumed to be aliases for the column names
  • index : boolean, default True
    Write row names (index)
  • index_label : string or sequence, or False, default None
    Column label for index column(s) if desired. If None is given, and header and index are True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. If False do not print fields for index names. Use index_label=False for easier importing in R
  • mode : str
    Python write mode, default ‘w’
  • encoding : string, optional
    A string representing the encoding to use in the output file, defaults to ‘ascii’ on Python 2 and ‘utf-8’ on Python 3.
  • compression : string, optional
    a string representing the compression to use in the output file, allowed values are ‘gzip’, ‘bz2’, ‘xz’, only used when the first argument is a filename
  • line_terminator : string, default ‘\n’
    The newline character or character sequence to use in the output file
  • quoting : optional constant from csv module
    defaults to csv.QUOTE_MINIMAL. If you have set a float_format then floats are converted to strings and thus csv.QUOTE_NONNUMERIC will treat them as non-numeric
  • quotechar : string (length 1), default ‘”’
    character used to quote fields
  • doublequote : boolean, default True
    Control quoting of quotechar inside a field
  • escapechar : string (length 1), default None
    character used to escape sep and quotechar when appropriate
  • chunksize : int or None
    rows to write at a time
  • tupleize_cols : boolean, default False
    Deprecated since version 0.21.0: This argument will be removed and will always write each row of the multi-index as a separate row in the CSV file. Write MultiIndex columns as a list of tuples (if True) or in the new, expanded format, where each MultiIndex column is a row in the CSV (if False).
  • date_format : string, default None
    Format string for datetime objects
  • decimal: string, default ‘.’
    Character recognized as decimal separator. E.g. use ‘,’ for European data

注意在输出文件的时候,检查原有的dataframe是否有header,写入文件的时候会默认加上header。此外在需要index的时候,选择默认的index=True。一般情况下index为数字的时候,index=False。

注意:常见的float_format参数设置为float_format='%.3f'。 the keyword arguments decimal= and float_format= only work on data columns, not on the index.

自己写的代码示例:

def strToDate(strSample):
    return datetime.strptime(strSample, "%Y%m%d")

card_df = pd.read_csv('cards.csv', usecols=[1,3,9], header=0, names=['Date', 'Fee', 'TrCode'],
    dtype={'Date':str, 'Fee':np.float32, 'TrCode':np.int32})
card_df['Date'] = card_df['Date'].map(strToDate)
card_df = card_df['Fee'].groupby([card_df['Date'], card_df['TrCode']]).sum()
card_df = card_df.unstack('TrCode')
card_df.to_csv("card_out.csv", na_rep=0)

另外的一个自己写的例子:

card_df = pd.read_csv('cards.csv', usecols=[0,1,2,3,9], header=0, names=['StuId', 'Date', 'Time', 'Fee', 'TrCode'],
	dtype={'StuId':str, 'Date':str, 'Time':np.int32, 'Fee':np.float32, 'TrCode':np.int32})
card_df['Date'] = card_df['Date'].map(strToDate)
card_df['Time'] = card_df['Time'].map(transfer_time_to_section)
sub_card = (card_df['TrCode'] == 210) & (card_df['Fee'] <= 50.0)
card_df_grouped_count = card_df[sub_card]['Fee'].groupby([card_df['StuId']]).count()
card_df_grouped_fee = card_df[sub_card]['Fee'].groupby([card_df['StuId'], card_df['Date'],card_df['Time']]).sum().unstack('Time')
card_df_grouped_fee = card_df_grouped_fee.groupby(level='StuId', axis=0).mean()
card_df_grouped_fee['Count'] = card_df_grouped_count
card_df_grouped_fee.to_csv("cards_out.csv", na_rep=0)

Pandas读取csv出现Memory Error

Windows memory limitation

Memory errors happens a lot with python when using the 32bit version in Windows. This is because 32bit processes only gets 2GB of memory to play with by default.

Tricks for lowering memory usage

If you are not using 32bit python in windows but are looking to improve on your memory efficiency while reading csv files, there is a trick.

The pandas.read_csv function takes an option called dtype. This lets pandas know what types exist inside your csv data.

How this works

By default, pandas will try to guess what dtypes your csv file has. This is a very heavy operation because while it is determining the dtype, it has to keep all raw data as objects (strings) in memory.

Example

Let’s say your csv looks like this:

name, age, birthday Alice, 30, 1985-01-01 Bob, 35, 1980-01-01 Charlie, 25, 1990-01-01 This example is of course no problem to read into memory, but it’s just an example.

If pandas were to read the above csv file without any dtype option, the age would be stored as strings in memory until pandas has read enough lines of the csv file to make a qualified guess.

I think the default in pandas is to read 1,000,000 rows before guessing the dtype.

Solution

By specifying dtype={‘age’:int} as an option to the .read_csv() will let pandas know that age should be interpreted as a number. This saves you lots of memory.

Problem with corrupt data

However, if your csv file would be corrupted, like this:

name, age, birthday Alice, 30, 1985-01-01 Bob, 35, 1980-01-01 Charlie, 25, 1990-01-01 Dennis, 40+, None-Ur-Bz Then specifying dtype={‘age’:int} will break the .read_csv() command, because it cannot cast “40+” to int. So sanitize your data carefully!

Here you can see how the memory usage of a pandas dataframe is a lot higher when floats are kept as strings:

Try it yourself

df = pd.DataFrame(pd.np.random.choice([‘1.0’, ‘0.6666667’, ‘150000.1’],(100000, 10))) resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

224544 (~224 MB)

df = pd.DataFrame(pd.np.random.choice([1.0, 0.6666667, 150000.1],(100000, 10))) resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

79560 (~79 MB)


Reference

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html
https://www.jianshu.com/p/366aa5daaba9
https://stackoverflow.com/questions/17557074/memory-error-when-using-pandas-read-csv