title stringlengths 1 185 | diff stringlengths 0 32.2M | body stringlengths 0 123k ⌀ | url stringlengths 57 58 | created_at stringlengths 20 20 | closed_at stringlengths 20 20 | merged_at stringlengths 20 20 ⌀ | updated_at stringlengths 20 20 |
|---|---|---|---|---|---|---|---|
DOC: fix formatting read_csv comment kwarg explanation | diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 72d8b2720c747..2034d4fa899ce 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -33,8 +33,9 @@ class ParserWarning(Warning):
Parameters
----------
-filepath_or_buffer : string or file handle / StringIO. The string could be
- a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a
+filepath_or_buffer : 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.csv
%s
@@ -59,7 +60,8 @@ class ParserWarning(Warning):
dialect : string or csv.Dialect instance, default None
If None defaults to Excel dialect. Ignored if sep longer than 1 char
See csv.Dialect documentation for more details
-header : int row number(s) to use as the column names, and the start of the
+header : int, list of ints
+ Row number(s) to use as the column names, and the start of the
data. Defaults to 0 if no ``names`` passed, otherwise ``None``. Explicitly
pass ``header=0`` to be able to replace existing names. The header can be
a list of integers that specify row locations for a multi-index on the
@@ -78,7 +80,7 @@ class ParserWarning(Warning):
names : array-like
List of column names to use. If file contains no header row, then you
should explicitly pass header=None
-prefix : string or None (default)
+prefix : string, default None
Prefix to add to column numbers when no header, e.g 'X' for X0, X1, ...
na_values : list-like or dict, default None
Additional strings to recognize as NA/NaN. If dict passed, specific
@@ -113,7 +115,7 @@ class ParserWarning(Warning):
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
- '#empty\n1,2,3\na,b,c' with `header=0` will result in '1,2,3' being
+ '#empty\\na,b,c\\n1,2,3' with `header=0` will result in 'a,b,c' being
treated as the header.
decimal : str, default '.'
Character to recognize as decimal point. E.g. use ',' for European data
| `\n` -> `\\n` to render correclty (and some other small things)
| https://api.github.com/repos/pandas-dev/pandas/pulls/8563 | 2014-10-15T19:23:20Z | 2014-10-24T11:16:24Z | 2014-10-24T11:16:24Z | 2014-10-24T11:16:24Z |
API: Unify SQLTable code for fallback and SQLAlchemy mode and move differences into database class | diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 9baae0330926d..90af526acc17b 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -293,8 +293,8 @@ def read_sql_table(table_name, con, schema=None, index_col=None,
schema : string, default None
Name of SQL schema in database to query (if database flavor
supports this). If None, use default schema (default).
- index_col : string, optional
- Column to set as index
+ index_col : string or list of strings, optional
+ Column(s) to set as index
coerce_float : boolean, default True
Attempt to convert values to non-string, non-numeric objects (like
decimal.Decimal) to floating point. Can result in loss of Precision.
@@ -323,6 +323,7 @@ def read_sql_table(table_name, con, schema=None, index_col=None,
read_sql
"""
+
if not _is_sqlalchemy_engine(con):
raise NotImplementedError("read_sql_table only supported for "
"SQLAlchemy engines.")
@@ -361,8 +362,8 @@ def read_sql_query(sql, con, index_col=None, coerce_float=True, params=None,
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
- index_col : string, optional
- Column name to use as index for the returned DataFrame object.
+ index_col : string or list of strings, optional
+ Column(s) name to use as index for the returned DataFrame object.
coerce_float : boolean, default True
Attempt to convert values to non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets
@@ -414,8 +415,8 @@ def read_sql(sql, con, index_col=None, coerce_float=True, params=None,
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
- index_col : string, optional
- column name to use as index for the returned DataFrame object.
+ index_col : string or list of strings, optional
+ column(s) name to use as index for the returned DataFrame object.
coerce_float : boolean, default True
Attempt to convert values to non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets
@@ -572,7 +573,7 @@ def has_table(table_name, con, flavor='sqlite', schema=None):
def pandasSQL_builder(con, flavor=None, schema=None, meta=None,
is_cursor=False):
"""
- Convenience function to return the correct PandasSQL subclass based on the
+ Convenience function to return the correct SQLBackend subclass based on the
provided parameters
"""
# When support for DBAPI connections is removed,
@@ -588,8 +589,6 @@ def pandasSQL_builder(con, flavor=None, schema=None, meta=None,
class SQLTable(PandasObject):
"""
For mapping Pandas tables to SQL tables.
- Uses fact that table is reflected by SQLAlchemy to
- do better type convertions.
Also holds various flags needed to avoid having to
pass them between functions all the time.
"""
@@ -601,52 +600,57 @@ def __init__(self, name, pandas_sql_engine, frame=None, index=True,
self.pd_sql = pandas_sql_engine
self.prefix = prefix
self.frame = frame
- self.index = self._index_name(index, index_label)
self.schema = schema
self.if_exists = if_exists
self.keys = keys
- if frame is not None:
- # We want to initialize based on a dataframe
- self.table = self._create_table_setup()
- else:
- # no data provided, read-only mode
- self.table = self.pd_sql.get_table(self.name, self.schema)
+ self.index = None
+
+ # We want to initialize based on a dataframe
+ if index is True:
+ # Use indexes from dataframe
+ nlevels = self.frame.index.nlevels
+ # if index_label is specified, set this as index name(s)
+ if index_label is not None:
+ if not isinstance(index_label, list):
+ index_label = [index_label]
+ if len(index_label) != nlevels:
+ raise ValueError(
+ "Length of 'index_label' should match number of "
+ "levels, which is {0}".format(nlevels))
+ else:
+ self.index = index_label
+ else:
+ # return the used column labels for the index columns
+ if (nlevels == 1 and 'index' not in self.frame.columns
+ and self.frame.index.name is None):
+ self.index = ['index']
+ else:
+ self.index = [l if l is not None else "level_{0}".format(i)
+ for i, l in enumerate(self.frame.index.names)]
- if self.table is None:
- raise ValueError("Could not init table '%s'" % name)
+ self.backend_table = self.pd_sql.get_backend_table_object(name,
+ frame, keys=keys, schema=schema, index=self.index)
def exists(self):
return self.pd_sql.has_table(self.name, self.schema)
- def sql_schema(self):
- from sqlalchemy.schema import CreateTable
- return str(CreateTable(self.table).compile(self.pd_sql.engine))
-
- def _execute_create(self):
- # Inserting table into database, add to MetaData object
- self.table = self.table.tometadata(self.pd_sql.meta)
- self.table.create()
-
def create(self):
if self.exists():
if self.if_exists == 'fail':
raise ValueError("Table '%s' already exists." % self.name)
elif self.if_exists == 'replace':
self.pd_sql.drop_table(self.name, self.schema)
- self._execute_create()
+ self.pd_sql.create_table(self.backend_table)
elif self.if_exists == 'append':
pass
else:
raise ValueError(
"'{0}' is not valid for if_exists".format(self.if_exists))
else:
- self._execute_create()
+ self.pd_sql.create_table(self.backend_table)
- def insert_statement(self):
- return self.table.insert()
-
- def insert_data(self):
+ def _data_for_insert(self):
if self.index is not None:
temp = self.frame.copy()
temp.index.names = self.index
@@ -682,12 +686,8 @@ def insert_data(self):
return column_names, data_list
- def _execute_insert(self, conn, keys, data_iter):
- data = [dict((k, v) for k, v in zip(keys, row)) for row in data_iter]
- conn.execute(self.insert_statement(), data)
-
def insert(self, chunksize=None):
- keys, data_list = self.insert_data()
+ cols, data_list = self._data_for_insert()
nrows = len(self.frame)
@@ -701,7 +701,7 @@ def insert(self, chunksize=None):
chunks = int(nrows / chunksize) + 1
- with self.pd_sql.run_transaction() as conn:
+ with self.pd_sql.run_transaction() as trans:
for i in range(chunks):
start_i = i * chunksize
end_i = min((i + 1) * chunksize, nrows)
@@ -709,240 +709,178 @@ def insert(self, chunksize=None):
break
chunk_iter = zip(*[arr[start_i:end_i] for arr in data_list])
- self._execute_insert(conn, keys, chunk_iter)
+ self.pd_sql.insert_data(trans, self.backend_table, cols, chunk_iter)
+
+
+class SQLBackend(PandasObject):
+ """Base class providing methods to read and write frames to/form a
+ database. These calls methods that backend-specific subclasses
+ must implement.
+ """
+
- def _query_iterator(self, result, chunksize, columns, coerce_float=True,
- parse_dates=None):
+ def _query_iterator(self, result, chunksize, columns, index_col=None,
+ coerce_float=True, parse_dates=None):
"""Return generator through chunked result set"""
while True:
data = result.fetchmany(chunksize)
if not data:
+ self._close_result(result)
break
else:
- self.frame = DataFrame.from_records(
- data, columns=columns, coerce_float=coerce_float)
+ yield _wrap_result(data, columns, index_col=index_col,
+ coerce_float=coerce_float,
+ parse_dates=parse_dates)
- self._harmonize_columns(parse_dates=parse_dates)
+ def read_query(self, sql, index_col=None, coerce_float=True,
+ parse_dates=None, params=None, chunksize=None):
+ """Read SQL query into a DataFrame.
- if self.index is not None:
- self.frame.set_index(self.index, inplace=True)
+ Parameters
+ ----------
+ sql : string
+ SQL query to be executed
+ index_col : string, optional
+ Column name to use as index for the returned DataFrame object.
+ coerce_float : boolean, default True
+ Attempt to convert values to non-string, non-numeric objects (like
+ decimal.Decimal) to floating point, useful for SQL result sets
+ params : list, tuple or dict, optional
+ List of parameters to pass to execute method. The syntax used
+ to pass parameters is database driver dependent. Check your
+ database driver documentation for which of the five syntax styles,
+ described in PEP 249's paramstyle, is supported.
+ Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
+ parse_dates : list or dict
+ - List of column names to parse as dates
+ - Dict of ``{column_name: format string}`` where format string is
+ strftime compatible in case of parsing string times or is one of
+ (D, s, ns, ms, us) in case of parsing integer timestamps
+ - Dict of ``{column_name: arg dict}``, where the arg dict corresponds
+ to the keyword arguments of :func:`pandas.to_datetime`
+ Especially useful with databases without native Datetime support,
+ such as SQLite
- yield self.frame
+ Returns
+ -------
+ DataFrame
- def read(self, coerce_float=True, parse_dates=None, columns=None,
- chunksize=None):
+ See also
+ --------
+ read_sql_table : Read SQL database table into a DataFrame
+ read_sql
- if columns is not None and len(columns) > 0:
- from sqlalchemy import select
- cols = [self.table.c[n] for n in columns]
- if self.index is not None:
- [cols.insert(0, self.table.c[idx]) for idx in self.index[::-1]]
- sql_select = select(cols)
- else:
- sql_select = self.table.select()
+ """
+ args = _convert_params(sql, params)
- result = self.pd_sql.execute(sql_select)
- column_names = result.keys()
+ result = self.execute(*args)
+ columns = self._get_result_columns(result)
if chunksize is not None:
- return self._query_iterator(result, chunksize, column_names,
+ return self._query_iterator(result, chunksize, columns,
+ index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates)
else:
- data = result.fetchall()
- self.frame = DataFrame.from_records(
- data, columns=column_names, coerce_float=coerce_float)
-
- self._harmonize_columns(parse_dates=parse_dates)
-
- if self.index is not None:
- self.frame.set_index(self.index, inplace=True)
-
- return self.frame
-
- def _index_name(self, index, index_label):
- # for writing: index=True to include index in sql table
- if index is True:
- nlevels = self.frame.index.nlevels
- # if index_label is specified, set this as index name(s)
- if index_label is not None:
- if not isinstance(index_label, list):
- index_label = [index_label]
- if len(index_label) != nlevels:
- raise ValueError(
- "Length of 'index_label' should match number of "
- "levels, which is {0}".format(nlevels))
- else:
- return index_label
- # return the used column labels for the index columns
- if (nlevels == 1 and 'index' not in self.frame.columns
- and self.frame.index.name is None):
- return ['index']
- else:
- return [l if l is not None else "level_{0}".format(i)
- for i, l in enumerate(self.frame.index.names)]
-
- # for reading: index=(list of) string to specify column to set as index
- elif isinstance(index, string_types):
- return [index]
- elif isinstance(index, list):
- return index
- else:
- return None
-
- def _get_column_names_and_types(self, dtype_mapper):
- column_names_and_types = []
- if self.index is not None:
- for i, idx_label in enumerate(self.index):
- idx_type = dtype_mapper(
- self.frame.index.get_level_values(i))
- column_names_and_types.append((idx_label, idx_type, True))
+ data = self._fetchall_as_list(result)
+ self._close_result(result)
- column_names_and_types += [
- (str(self.frame.columns[i]),
- dtype_mapper(self.frame.iloc[:, i]),
- False)
- for i in range(len(self.frame.columns))
- ]
-
- return column_names_and_types
-
- def _create_table_setup(self):
- from sqlalchemy import Table, Column, PrimaryKeyConstraint
-
- column_names_and_types = \
- self._get_column_names_and_types(self._sqlalchemy_type)
-
- columns = [Column(name, typ, index=is_index)
- for name, typ, is_index in column_names_and_types]
-
- if self.keys is not None:
- pkc = PrimaryKeyConstraint(self.keys, name=self.name + '_pk')
- columns.append(pkc)
-
- schema = self.schema or self.pd_sql.meta.schema
-
- # At this point, attach to new metadata, only attach to self.meta
- # once table is created.
- from sqlalchemy.schema import MetaData
- meta = MetaData(self.pd_sql, schema=schema)
+ frame = _wrap_result(data, columns, index_col=index_col,
+ coerce_float=coerce_float,
+ parse_dates=parse_dates)
+ return frame
- return Table(self.name, meta, *columns, schema=schema)
+ read_sql = read_query
- def _harmonize_columns(self, parse_dates=None):
- """
- Make the DataFrame's column types align with the SQL table
- column types.
- Need to work around limited NA value support. Floats are always
- fine, ints must always be floats if there are Null values.
- Booleans are hard because converting bool column with None replaces
- all Nones with false. Therefore only convert bool if there are no
- NA values.
- Datetimes should already be converted to np.datetime64 if supported,
- but here we also force conversion if required
+ def to_sql(self, frame, name, if_exists='fail', index=True,
+ index_label=None, schema=None, chunksize=None):
"""
- # handle non-list entries for parse_dates gracefully
- if parse_dates is True or parse_dates is None or parse_dates is False:
- parse_dates = []
-
- if not hasattr(parse_dates, '__iter__'):
- parse_dates = [parse_dates]
-
- for sql_col in self.table.columns:
- col_name = sql_col.name
- try:
- df_col = self.frame[col_name]
- # the type the dataframe column should have
- col_type = self._numpy_type(sql_col.type)
-
- if col_type is datetime or col_type is date:
- if not issubclass(df_col.dtype.type, np.datetime64):
- self.frame[col_name] = _handle_date_column(df_col)
+ Write records stored in a DataFrame to a SQL database.
- elif col_type is float:
- # floats support NA, can always convert!
- self.frame[col_name] = df_col.astype(col_type, copy=False)
+ Parameters
+ ----------
+ frame : DataFrame
+ name : string
+ Name of SQL table
+ if_exists : {'fail', 'replace', 'append'}, default 'fail'
+ - fail: If table exists, do nothing.
+ - replace: If table exists, drop it, recreate it, and insert data.
+ - append: If table exists, insert data. Create if does not exist.
+ index : boolean, default True
+ Write DataFrame index as a column
+ index_label : string or sequence, default None
+ Column label for index column(s). If None is given (default) and
+ `index` is True, then the index names are used.
+ A sequence should be given if the DataFrame uses MultiIndex.
+ schema : string, default None
+ Name of SQL schema in database to write to (if database flavor
+ supports this). If specified, this overwrites the default
+ schema of the SQLDatabase object. Not supported for fallback
+ database mode.
+ chunksize : int, default None
+ If not None, then rows will be written in batches of this size at a
+ time. If None, all rows will be written at once.
+
+ """
+ table = SQLTable(name, self, frame=frame, index=index,
+ if_exists=if_exists, index_label=index_label,
+ schema=schema)
+ table.create()
+ table.insert(chunksize)
- elif len(df_col) == df_col.count():
- # No NA values, can convert ints and bools
- if col_type is np.dtype('int64') or col_type is bool:
- self.frame[col_name] = df_col.astype(col_type, copy=False)
+ def has_table(self, table_name, schema=None):
+ # Check whether database has a table. Subclasses must implement.
+ raise NotImplementedError
+
+ def drop_table(self, table_name, schema=None):
+ # Drop table table_name. Subclasses must implement.
+ raise NotImplementedError
- # Handle date parsing
- if col_name in parse_dates:
- try:
- fmt = parse_dates[col_name]
- except TypeError:
- fmt = None
- self.frame[col_name] = _handle_date_column(
- df_col, format=fmt)
+ def execute(self, *args, **kwargs):
+ # Execute statement on the database. Subclasses must implement.
+ raise NotImplementedError
- except KeyError:
- pass # this column not in results
+ def run_transaction(self):
+ # Returns a contextmanager for manager a transaction on the database.
+ raise NotImplementedError
- def _sqlalchemy_type(self, col):
- from sqlalchemy.types import (BigInteger, Float, Text, Boolean,
- DateTime, Date, Time)
+ def get_backend_table_object(self, table_name, schema=None):
+ # Return a backend table object.
+ raise NotImplementedError
- if com.is_datetime64_dtype(col):
- try:
- tz = col.tzinfo
- return DateTime(timezone=True)
- except:
- return DateTime
- if com.is_timedelta64_dtype(col):
- warnings.warn("the 'timedelta' type is not supported, and will be "
- "written as integer values (ns frequency) to the "
- "database.", UserWarning)
- return BigInteger
- elif com.is_float_dtype(col):
- return Float
- elif com.is_integer_dtype(col):
- # TODO: Refine integer size.
- return BigInteger
- elif com.is_bool_dtype(col):
- return Boolean
- inferred = lib.infer_dtype(com._ensure_object(col))
- if inferred == 'date':
- return Date
- if inferred == 'time':
- return Time
- return Text
+ def create_statement(self, backend_table):
+ # Return a SQL statement to create table corresponding to backend_table.
+ raise NotImplementedError
- def _numpy_type(self, sqltype):
- from sqlalchemy.types import Integer, Float, Boolean, DateTime, Date
+ def create_table(self, backend_table):
+ # Create table in database correspond to backend_table object.
+ raise NotImplementedError
- if isinstance(sqltype, Float):
- return float
- if isinstance(sqltype, Integer):
- # TODO: Refine integer size.
- return np.dtype('int64')
- if isinstance(sqltype, DateTime):
- # Caution: np.datetime64 is also a subclass of np.number.
- return datetime
- if isinstance(sqltype, Date):
- return date
- if isinstance(sqltype, Boolean):
- return bool
- return object
+ def insert_data(self, trans, backend_table, keys, data_iter):
+ # Insert data from data_iter into backend_table within transaction trans.
+ raise NotImplementedError
-class PandasSQL(PandasObject):
- """
- Subclasses Should define read_sql and to_sql
- """
+def _get_column_names_and_types(frame, dtype_mapper, index):
+ column_names_and_types = []
+ if index is not None:
+ for i, idx_label in enumerate(index):
+ idx_type = dtype_mapper(
+ frame.index.get_level_values(i))
+ column_names_and_types.append((idx_label, idx_type, True))
- def read_sql(self, *args, **kwargs):
- raise ValueError("PandasSQL must be created with an SQLAlchemy engine"
- " or connection+sql flavor")
+ column_names_and_types += [
+ (str(frame.columns[i]),
+ dtype_mapper(frame.iloc[:, i]),
+ False)
+ for i in range(len(frame.columns))
+ ]
- def to_sql(self, *args, **kwargs):
- raise ValueError("PandasSQL must be created with an SQLAlchemy engine"
- " or connection+sql flavor")
+ return column_names_and_types
-class SQLDatabase(PandasSQL):
+class SQLDatabase(SQLBackend):
"""
This class enables convertion between DataFrame and SQL databases
using SQLAlchemy to handle DataBase abstraction
@@ -970,13 +908,6 @@ def __init__(self, engine, schema=None, meta=None):
self.meta = meta
- def run_transaction(self):
- return self.engine.begin()
-
- def execute(self, *args, **kwargs):
- """Simple passthrough to SQLAlchemy engine"""
- return self.engine.execute(*args, **kwargs)
-
def read_table(self, table_name, index_col=None, coerce_float=True,
parse_dates=None, columns=None, schema=None,
chunksize=None):
@@ -986,8 +917,8 @@ def read_table(self, table_name, index_col=None, coerce_float=True,
----------
table_name : string
Name of SQL table in database
- index_col : string, optional
- Column to set as index
+ index_col : string or list of strings, optional
+ Column(s) to set as index
coerce_float : boolean, default True
Attempt to convert values to non-string, non-numeric objects
(like decimal.Decimal) to floating point. This can result in
@@ -1021,148 +952,224 @@ def read_table(self, table_name, index_col=None, coerce_float=True,
SQLDatabase.read_query
"""
- table = SQLTable(table_name, self, index=index_col, schema=schema)
- return table.read(coerce_float=coerce_float,
- parse_dates=parse_dates, columns=columns,
- chunksize=chunksize)
- @staticmethod
- def _query_iterator(result, chunksize, columns, index_col=None,
- coerce_float=True, parse_dates=None):
- """Return generator through chunked result set"""
+ table = self.get_table(table_name)
- while True:
- data = result.fetchmany(chunksize)
- if not data:
- break
- else:
- yield _wrap_result(data, columns, index_col=index_col,
- coerce_float=coerce_float,
- parse_dates=parse_dates)
-
- def read_query(self, sql, index_col=None, coerce_float=True,
- parse_dates=None, params=None, chunksize=None):
- """Read SQL query into a DataFrame.
-
- Parameters
- ----------
- sql : string
- SQL query to be executed
- index_col : string, optional
- Column name to use as index for the returned DataFrame object.
- coerce_float : boolean, default True
- Attempt to convert values to non-string, non-numeric objects (like
- decimal.Decimal) to floating point, useful for SQL result sets
- params : list, tuple or dict, optional
- List of parameters to pass to execute method. The syntax used
- to pass parameters is database driver dependent. Check your
- database driver documentation for which of the five syntax styles,
- described in PEP 249's paramstyle, is supported.
- Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
- parse_dates : list or dict
- - List of column names to parse as dates
- - Dict of ``{column_name: format string}`` where format string is
- strftime compatible in case of parsing string times or is one of
- (D, s, ns, ms, us) in case of parsing integer timestamps
- - Dict of ``{column_name: arg dict}``, where the arg dict corresponds
- to the keyword arguments of :func:`pandas.to_datetime`
- Especially useful with databases without native Datetime support,
- such as SQLite
-
- Returns
- -------
- DataFrame
-
- See also
- --------
- read_sql_table : Read SQL database table into a DataFrame
- read_sql
+ if isinstance(index_col, string_types):
+ index = [index_col,]
+ elif isinstance(index_col, list):
+ index = index_col
+ else:
+ index = None
- """
- args = _convert_params(sql, params)
+ if columns is not None and len(columns) > 0:
+ from sqlalchemy import select
+ cols = [table.c[n] for n in columns]
+ if index is not None:
+ [cols.insert(0, table.c[idx]) for idx in index[::-1]]
+ sql_select = select(cols)
+ else:
+ sql_select = table.select()
- result = self.execute(*args)
- columns = result.keys()
+ result = self.execute(sql_select)
+ column_names = result.keys()
if chunksize is not None:
- return self._query_iterator(result, chunksize, columns,
- index_col=index_col,
+ return self._query_iterator(result, chunksize, column_names,
coerce_float=coerce_float,
parse_dates=parse_dates)
else:
data = result.fetchall()
- frame = _wrap_result(data, columns, index_col=index_col,
- coerce_float=coerce_float,
- parse_dates=parse_dates)
+ frame = DataFrame.from_records(
+ data, columns=column_names, coerce_float=coerce_float)
+
+ frame = self._harmonize_columns(table, frame, parse_dates=parse_dates)
+
+ if index is not None:
+ frame.set_index(index, inplace=True)
+
return frame
- read_sql = read_query
+ def current_schema(self, schema=None):
+ return schema or self.meta.schema
- def to_sql(self, frame, name, if_exists='fail', index=True,
- index_label=None, schema=None, chunksize=None):
- """
- Write records stored in a DataFrame to a SQL database.
+ def _get_result_columns(self, result):
+ return result.keys()
- Parameters
- ----------
- frame : DataFrame
- name : string
- Name of SQL table
- if_exists : {'fail', 'replace', 'append'}, default 'fail'
- - fail: If table exists, do nothing.
- - replace: If table exists, drop it, recreate it, and insert data.
- - append: If table exists, insert data. Create if does not exist.
- index : boolean, default True
- Write DataFrame index as a column
- index_label : string or sequence, default None
- Column label for index column(s). If None is given (default) and
- `index` is True, then the index names are used.
- A sequence should be given if the DataFrame uses MultiIndex.
- schema : string, default None
- Name of SQL schema in database to write to (if database flavor
- supports this). If specified, this overwrites the default
- schema of the SQLDatabase object.
- chunksize : int, default None
- If not None, then rows will be written in batches of this size at a
- time. If None, all rows will be written at once.
-
- """
- table = SQLTable(name, self, frame=frame, index=index,
- if_exists=if_exists, index_label=index_label,
- schema=schema)
- table.create()
- table.insert(chunksize)
- # check for potentially case sensitivity issues (GH7815)
- if name not in self.engine.table_names(schema=schema or self.meta.schema):
- warnings.warn("The provided table name '{0}' is not found exactly "
- "as such in the database after writing the table, "
- "possibly due to case sensitivity issues. Consider "
- "using lower case table names.".format(name), UserWarning)
+ def _fetchall_as_list(self, result):
+ return result.fetchall()
- @property
- def tables(self):
- return self.meta.tables
+ def _close_result(self, result):
+ pass
- def has_table(self, name, schema=None):
- return self.engine.has_table(name, schema or self.meta.schema)
+ def has_table(self, table_name, schema=None):
+ return self.engine.has_table(table_name, self.current_schema(schema))
def get_table(self, table_name, schema=None):
- schema = schema or self.meta.schema
+ schema = self.current_schema(schema)
if schema:
return self.meta.tables.get('.'.join([schema, table_name]))
else:
return self.meta.tables.get(table_name)
def drop_table(self, table_name, schema=None):
- schema = schema or self.meta.schema
+ schema = self.current_schema(schema)
if self.engine.has_table(table_name, schema):
self.meta.reflect(only=[table_name], schema=schema)
self.get_table(table_name, schema).drop()
self.meta.clear()
- def _create_sql_schema(self, frame, table_name, keys=None):
- table = SQLTable(table_name, self, frame=frame, index=False, keys=keys)
- return str(table.sql_schema())
+ def execute(self, *args, **kwargs):
+ """Simple passthrough to SQLAlchemy engine"""
+ return self.engine.execute(*args, **kwargs)
+
+ def run_transaction(self):
+ return self.engine.begin()
+
+ def get_backend_table_object(self, name, frame, keys=None, schema=None,
+ index=None):
+ from sqlalchemy import Table, Column, PrimaryKeyConstraint
+
+ column_names_and_types = \
+ _get_column_names_and_types(frame, self._sqlalchemy_type, index)
+
+ columns = [Column(colname, typ, index=is_index)
+ for colname, typ, is_index in column_names_and_types]
+
+ if keys is not None:
+ pkc = PrimaryKeyConstraint(keys, name=self.name + '_pk')
+ columns.append(pkc)
+
+ schema = self.current_schema(schema)
+
+ # At this point, attach to new metadata, only attach to self.meta
+ # once table is created.
+ from sqlalchemy.schema import MetaData
+ meta = MetaData(self.engine, schema=schema)
+
+ return Table(name, meta, *columns, schema=schema)
+
+ def create_statement(self, backend_table):
+ from sqlalchemy.schema import CreateTable
+ return str(CreateTable(backend_table).compile(self.engine))
+
+ def insert_data(self, trans, backend_table, cols, data_iter):
+ data = [dict((k, v) for k, v in zip(cols, row)) for row in data_iter]
+ trans.execute(backend_table.insert(), data)
+
+ def create_table(self, backend_table):
+ # Inserting table into database, add to MetaData object
+ backend_table = backend_table.tometadata(self.meta)
+ backend_table.create()
+
+ # check for potentially case sensitivity issues (GH7815)
+ if not self.has_table(backend_table.name,
+ schema=self.current_schema(backend_table.schema)):
+ warnings.warn("The provided table name '{0}' is not found exactly "
+ "as such in the database after writing the table, "
+ "possibly due to case sensitivity issues. Consider "
+ "using lower case table names.".format(backend_table.name),
+ UserWarning)
+
+ def _sqlalchemy_type(self, col):
+ from sqlalchemy.types import (BigInteger, Float, Text, Boolean,
+ DateTime, Date, Time)
+
+ if com.is_datetime64_dtype(col):
+ try:
+ tz = col.tzinfo
+ return DateTime(timezone=True)
+ except:
+ return DateTime
+ if com.is_timedelta64_dtype(col):
+ warnings.warn("the 'timedelta' type is not supported, and will be "
+ "written as integer values (ns frequency) to the "
+ "database.", UserWarning)
+ return BigInteger
+ elif com.is_float_dtype(col):
+ return Float
+ elif com.is_integer_dtype(col):
+ # TODO: Refine integer size.
+ return BigInteger
+ elif com.is_bool_dtype(col):
+ return Boolean
+ inferred = lib.infer_dtype(com._ensure_object(col))
+ if inferred == 'date':
+ return Date
+ if inferred == 'time':
+ return Time
+ return Text
+
+ def _harmonize_columns(self, table, frame, parse_dates=None):
+ """
+ Make the DataFrame's column types align with the SQL table
+ column types.
+ Need to work around limited NA value support. Floats are always
+ fine, ints must always be floats if there are Null values.
+ Booleans are hard because converting bool column with None replaces
+ all Nones with false. Therefore only convert bool if there are no
+ NA values.
+ Datetimes should already be converted to np.datetime64 if supported,
+ but here we also force conversion if required
+ """
+ # handle non-list entries for parse_dates gracefully
+ if parse_dates is True or parse_dates is None or parse_dates is False:
+ parse_dates = []
+
+ if not hasattr(parse_dates, '__iter__'):
+ parse_dates = [parse_dates]
+
+ for sql_col in table.columns:
+ col_name = sql_col.name
+ try:
+ df_col = frame[col_name]
+ # the type the dataframe column should have
+ col_type = self._numpy_type(sql_col.type)
+
+ if col_type is datetime or col_type is date:
+ if not issubclass(df_col.dtype.type, np.datetime64):
+ frame[col_name] = _handle_date_column(df_col)
+
+ elif col_type is float:
+ # floats support NA, can always convert!
+ frame[col_name] = df_col.astype(col_type, copy=False)
+
+ elif len(df_col) == df_col.count():
+ # No NA values, can convert ints and bools
+ if col_type is np.dtype('int64') or col_type is bool:
+ frame[col_name] = df_col.astype(col_type,
+ copy=False)
+
+ # Handle date parsing
+ if col_name in parse_dates:
+ try:
+ fmt = parse_dates[col_name]
+ except TypeError:
+ fmt = None
+ frame[col_name] = _handle_date_column(
+ df_col, format=fmt)
+
+ except KeyError:
+ pass # this column not in results
+
+ return frame
+
+ def _numpy_type(self, sqltype):
+ from sqlalchemy.types import Integer, Float, Boolean, DateTime, Date
+
+ if isinstance(sqltype, Float):
+ return float
+ if isinstance(sqltype, Integer):
+ # TODO: Refine integer size.
+ return np.dtype('int64')
+ if isinstance(sqltype, DateTime):
+ # Caution: np.datetime64 is also a subclass of np.number.
+ return datetime
+ if isinstance(sqltype, Date):
+ return date
+ if isinstance(sqltype, Boolean):
+ return bool
+ return object
# ---- SQL without SQLAlchemy ---
@@ -1220,110 +1227,15 @@ def _create_sql_schema(self, frame, table_name, keys=None):
"underscores.")
-class SQLiteTable(SQLTable):
- """
- Patch the SQLTable for fallback support.
- Instead of a table variable just use the Create Table statement.
- """
-
- def sql_schema(self):
- return str(";\n".join(self.table))
-
- def _execute_create(self):
- with self.pd_sql.run_transaction() as conn:
- for stmt in self.table:
- conn.execute(stmt)
-
- def insert_statement(self):
- names = list(map(str, self.frame.columns))
- flv = self.pd_sql.flavor
- br_l = _SQL_SYMB[flv]['br_l'] # left val quote char
- br_r = _SQL_SYMB[flv]['br_r'] # right val quote char
- wld = _SQL_SYMB[flv]['wld'] # wildcard char
-
- if self.index is not None:
- [names.insert(0, idx) for idx in self.index[::-1]]
-
- bracketed_names = [br_l + column + br_r for column in names]
- col_names = ','.join(bracketed_names)
- wildcards = ','.join([wld] * len(names))
- insert_statement = 'INSERT INTO %s (%s) VALUES (%s)' % (
- self.name, col_names, wildcards)
- return insert_statement
-
- def _execute_insert(self, conn, keys, data_iter):
- data_list = list(data_iter)
- conn.executemany(self.insert_statement(), data_list)
-
- def _create_table_setup(self):
- """
- Return a list of SQL statement that create a table reflecting the
- structure of a DataFrame. The first entry will be a CREATE TABLE
- statement while the rest will be CREATE INDEX statements
- """
- column_names_and_types = \
- self._get_column_names_and_types(self._sql_type_name)
-
- pat = re.compile('\s+')
- column_names = [col_name for col_name, _, _ in column_names_and_types]
- if any(map(pat.search, column_names)):
- warnings.warn(_SAFE_NAMES_WARNING)
-
- flv = self.pd_sql.flavor
-
- br_l = _SQL_SYMB[flv]['br_l'] # left val quote char
- br_r = _SQL_SYMB[flv]['br_r'] # right val quote char
-
- create_tbl_stmts = [(br_l + '%s' + br_r + ' %s') % (cname, ctype)
- for cname, ctype, _ in column_names_and_types]
- if self.keys is not None and len(self.keys):
- cnames_br = ",".join([br_l + c + br_r for c in self.keys])
- create_tbl_stmts.append(
- "CONSTRAINT {tbl}_pk PRIMARY KEY ({cnames_br})".format(
- tbl=self.name, cnames_br=cnames_br))
-
- create_stmts = ["CREATE TABLE " + self.name + " (\n" +
- ',\n '.join(create_tbl_stmts) + "\n)"]
-
- ix_cols = [cname for cname, _, is_index in column_names_and_types
- if is_index]
- if len(ix_cols):
- cnames = "_".join(ix_cols)
- cnames_br = ",".join([br_l + c + br_r for c in ix_cols])
- create_stmts.append(
- "CREATE INDEX ix_{tbl}_{cnames} ON {tbl} ({cnames_br})".format(
- tbl=self.name, cnames=cnames, cnames_br=cnames_br))
-
- return create_stmts
-
- def _sql_type_name(self, col):
- pytype = col.dtype.type
- pytype_name = "text"
- if issubclass(pytype, np.floating):
- pytype_name = "float"
- elif com.is_timedelta64_dtype(pytype):
- warnings.warn("the 'timedelta' type is not supported, and will be "
- "written as integer values (ns frequency) to the "
- "database.", UserWarning)
- pytype_name = "int"
- elif issubclass(pytype, np.integer):
- pytype_name = "int"
- elif issubclass(pytype, np.datetime64) or pytype is datetime:
- # Caution: np.datetime64 is also a subclass of np.number.
- pytype_name = "datetime"
- elif issubclass(pytype, np.bool_):
- pytype_name = "bool"
- elif issubclass(pytype, np.object):
- pytype = lib.infer_dtype(com._ensure_object(col))
- if pytype == "date":
- pytype_name = "date"
- elif pytype == "time":
- pytype_name = "time"
-
- return _SQL_TYPES[pytype_name][self.pd_sql.flavor]
+class SQLiteBackendTable(PandasObject):
+ def __init__(self, name, frame, keys, index):
+ self.name = name
+ self.frame = frame
+ self.keys = keys
+ self.index = index
-class SQLiteDatabase(PandasSQL):
+class SQLiteDatabase(SQLBackend):
"""
Version of SQLDatabase to support sqlite connections (fallback without
sqlalchemy). This should only be used internally.
@@ -1378,88 +1290,27 @@ def execute(self, *args, **kwargs):
" to rollback" % (args[0], exc))
raise_with_traceback(ex)
- ex = DatabaseError("Execution failed on sql '%s': %s" % (args[0], exc))
+ ex = DatabaseError("Execution failed on sql '%s': %s" %
+ (args[0], exc))
raise_with_traceback(ex)
- @staticmethod
- def _query_iterator(cursor, chunksize, columns, index_col=None,
- coerce_float=True, parse_dates=None):
- """Return generator through chunked result set"""
-
- while True:
- data = cursor.fetchmany(chunksize)
- if not data:
- cursor.close()
- break
- else:
- yield _wrap_result(data, columns, index_col=index_col,
- coerce_float=coerce_float,
- parse_dates=parse_dates)
-
- def read_query(self, sql, index_col=None, coerce_float=True, params=None,
- parse_dates=None, chunksize=None):
-
- args = _convert_params(sql, params)
- cursor = self.execute(*args)
- columns = [col_desc[0] for col_desc in cursor.description]
-
- if chunksize is not None:
- return self._query_iterator(cursor, chunksize, columns,
- index_col=index_col,
- coerce_float=coerce_float,
- parse_dates=parse_dates)
- else:
- data = self._fetchall_as_list(cursor)
- cursor.close()
-
- frame = _wrap_result(data, columns, index_col=index_col,
- coerce_float=coerce_float,
- parse_dates=parse_dates)
- return frame
-
+ def _get_result_columns(self, result):
+ return [col_desc[0] for col_desc in result.description]
+
def _fetchall_as_list(self, cur):
result = cur.fetchall()
if not isinstance(result, list):
result = list(result)
return result
- def to_sql(self, frame, name, if_exists='fail', index=True,
- index_label=None, schema=None, chunksize=None):
- """
- Write records stored in a DataFrame to a SQL database.
-
- Parameters
- ----------
- frame: DataFrame
- name: name of SQL table
- if_exists: {'fail', 'replace', 'append'}, default 'fail'
- fail: If table exists, do nothing.
- replace: If table exists, drop it, recreate it, and insert data.
- append: If table exists, insert data. Create if does not exist.
- index : boolean, default True
- Write DataFrame index as a column
- index_label : string or sequence, default None
- Column label for index column(s). If None is given (default) and
- `index` is True, then the index names are used.
- A sequence should be given if the DataFrame uses MultiIndex.
- schema : string, default None
- Ignored parameter included for compatability with SQLAlchemy
- version of ``to_sql``.
- chunksize : int, default None
- If not None, then rows will be written in batches of this
- size at a time. If None, all rows will be written at once.
-
- """
- table = SQLiteTable(name, self, frame=frame, index=index,
- if_exists=if_exists, index_label=index_label)
- table.create()
- table.insert(chunksize)
+ def _close_result(self, cur):
+ cur.close()
- def has_table(self, name, schema=None):
+ def has_table(self, table_name, schema=None):
flavor_map = {
'sqlite': ("SELECT name FROM sqlite_master "
- "WHERE type='table' AND name='%s';") % name,
- 'mysql': "SHOW TABLES LIKE '%s'" % name}
+ "WHERE type='table' AND name='%s';") % table_name,
+ 'mysql': "SHOW TABLES LIKE '%s'" % table_name}
query = flavor_map.get(self.flavor)
return len(self.execute(query).fetchall()) > 0
@@ -1471,10 +1322,106 @@ def drop_table(self, name, schema=None):
drop_sql = "DROP TABLE %s" % name
self.execute(drop_sql)
- def _create_sql_schema(self, frame, table_name, keys=None):
- table = SQLiteTable(table_name, self, frame=frame, index=False,
- keys=keys)
- return str(table.sql_schema())
+ def create_statement(self, backend_table):
+ return str(";\n".join(self._table_create_statements(backend_table)))
+
+ def create_table(self, backend_table):
+ with self.run_transaction() as conn:
+ for stmt in self._table_create_statements(backend_table):
+ conn.execute(stmt)
+
+ def insert_data(self, trans, backend_table, cols, data_iter):
+ data_list = list(data_iter)
+
+ names = list(map(str, backend_table.frame.columns))
+ flv = self.flavor
+ br_l = _SQL_SYMB[flv]['br_l'] # left val quote char
+ br_r = _SQL_SYMB[flv]['br_r'] # right val quote char
+ wld = _SQL_SYMB[flv]['wld'] # wildcard char
+
+ if backend_table.index is not None:
+ [names.insert(0, idx) for idx in backend_table.index[::-1]]
+
+ bracketed_names = [br_l + column + br_r for column in names]
+ col_names = ','.join(bracketed_names)
+ wildcards = ','.join([wld] * len(names))
+ insert_statement = 'INSERT INTO %s (%s) VALUES (%s)' % (
+ backend_table.name, col_names, wildcards)
+
+ trans.executemany(insert_statement, data_list)
+
+
+ def _sql_type_name(self, col):
+ pytype = col.dtype.type
+ pytype_name = "text"
+ if issubclass(pytype, np.floating):
+ pytype_name = "float"
+ elif com.is_timedelta64_dtype(pytype):
+ warnings.warn("the 'timedelta' type is not supported, and will be "
+ "written as integer values (ns frequency) to the "
+ "database.", UserWarning)
+ pytype_name = "int"
+ elif issubclass(pytype, np.integer):
+ pytype_name = "int"
+ elif issubclass(pytype, np.datetime64) or pytype is datetime:
+ # Caution: np.datetime64 is also a subclass of np.number.
+ pytype_name = "datetime"
+ elif issubclass(pytype, np.bool_):
+ pytype_name = "bool"
+ elif issubclass(pytype, np.object):
+ pytype = lib.infer_dtype(com._ensure_object(col))
+ if pytype == "date":
+ pytype_name = "date"
+ elif pytype == "time":
+ pytype_name = "time"
+
+ return _SQL_TYPES[pytype_name][self.flavor]
+
+ def _table_create_statements(self, backend_table):
+ """
+ Return a list of SQL statement that create a table reflecting the
+ structure of a DataFrame. The first entry will be a CREATE TABLE
+ statement while the rest will be CREATE INDEX statements
+ """
+ column_names_and_types = _get_column_names_and_types(
+ backend_table.frame, self._sql_type_name, backend_table.index)
+
+ pat = re.compile('\s+')
+ column_names = [col_name for col_name, _, _ in column_names_and_types]
+ if any(map(pat.search, column_names)):
+ warnings.warn(_SAFE_NAMES_WARNING)
+
+ flv = self.flavor
+
+ br_l = _SQL_SYMB[flv]['br_l'] # left val quote char
+ br_r = _SQL_SYMB[flv]['br_r'] # right val quote char
+
+ create_tbl_stmts = [(br_l + '%s' + br_r + ' %s') % (cname, ctype)
+ for cname, ctype, _ in column_names_and_types]
+ if backend_table.keys is not None and len(backend_table.keys):
+ cnames_br = ",".join([br_l + c + br_r for c in backend_table.keys])
+ create_tbl_stmts.append(
+ "CONSTRAINT {tbl}_pk PRIMARY KEY ({cnames_br})".format(
+ tbl=backend_table.name, cnames_br=cnames_br))
+
+ create_stmts = ["CREATE TABLE " + backend_table.name + " (\n" +
+ ',\n '.join(create_tbl_stmts) + "\n)"]
+
+ ix_cols = [cname for cname, _, is_index in column_names_and_types
+ if is_index]
+ if len(ix_cols):
+ cnames = "_".join(ix_cols)
+ cnames_br = ",".join([br_l + c + br_r for c in ix_cols])
+ create_stmts.append(
+ "CREATE INDEX ix_{tbl}_{cnames} ON {tbl} ({cnames_br})".format(
+ tbl=backend_table.name, cnames=cnames, cnames_br=cnames_br))
+ return create_stmts
+
+
+ def get_backend_table_object(self, name, frame, keys=None, schema=None,
+ index=None):
+ return SQLiteBackendTable(name, frame, keys, index)
+
def get_schema(frame, name, flavor='sqlite', keys=None, con=None):
@@ -1500,7 +1447,8 @@ def get_schema(frame, name, flavor='sqlite', keys=None, con=None):
"""
pandas_sql = pandasSQL_builder(con=con, flavor=flavor)
- return pandas_sql._create_sql_schema(frame, name, keys=keys)
+ table = pandas_sql.get_backend_table_object(name, frame, keys=keys)
+ return pandas_sql.create_statement(table)
# legacy names, with depreciation warnings and copied docs
| In discussion of the SQL API in #7960 , it has been suggested that it may be possible to factor out differences in SQLAlchemy and fallback backend . This is an initial attempt to do so. Now `SQLTable` is uncoupled from the backend. `PandasSQL` is base class for `SQLDatabase` (SQLAlchemy backend) and `SQLiteDatabase` (fallback backend). This allows for the removal of some duplicate code.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8562 | 2014-10-15T19:03:15Z | 2016-01-20T14:15:53Z | null | 2022-10-13T00:16:11Z |
DOC/FIX: In R it's still levels... | diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst
index 3940ef623a099..3ee660bb85691 100644
--- a/doc/source/categorical.rst
+++ b/doc/source/categorical.rst
@@ -33,7 +33,7 @@ with R's ``factor``.
`Categoricals` are a pandas data type, which correspond to categorical variables in
statistics: a variable, which can take on only a limited, and usually fixed,
-number of possible values (`categories`; `categories` in R). Examples are gender, social class,
+number of possible values (`categories`; `levels` in R). Examples are gender, social class,
blood types, country affiliations, observation time or ratings via Likert scales.
In contrast to statistical categorical variables, categorical data might have an order (e.g.
| There was one repleacement to many: in R it's still "levels" and not "categories".
-> one word replacement in the docs
| https://api.github.com/repos/pandas-dev/pandas/pulls/8561 | 2014-10-15T16:26:19Z | 2014-10-15T17:35:37Z | 2014-10-15T17:35:37Z | 2014-10-15T17:35:45Z |
PERF: fixup datetime_index repr perf (GH8556) | diff --git a/pandas/core/format.py b/pandas/core/format.py
index 2773cc0c135c1..89973754a861c 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -2027,14 +2027,19 @@ def _format_datetime64_dateonly(x, nat_rep='NaT', date_format=None):
def _is_dates_only(values):
- for d in values:
- if isinstance(d, np.datetime64):
- d = Timestamp(d)
-
- if d is not None and not lib.checknull(d) and d._has_time_component():
- return False
- return True
+ # return a boolean if we are only dates (and don't have a timezone)
+ from pandas import DatetimeIndex
+ values = DatetimeIndex(values)
+ if values.tz is not None:
+ return False
+ values_int = values.asi8
+ consider_values = values_int != iNaT
+ one_day_nanos = (86400 * 1e9)
+ even_days = np.logical_and(consider_values, values_int % one_day_nanos != 0).sum() == 0
+ if even_days:
+ return True
+ return False
def _get_format_datetime64(is_dates_only, nat_rep='NaT', date_format=None):
diff --git a/vb_suite/index_object.py b/vb_suite/index_object.py
index de60a44e23a52..18e319f6ede55 100644
--- a/vb_suite/index_object.py
+++ b/vb_suite/index_object.py
@@ -108,7 +108,7 @@
# Constructing MultiIndex from cartesian product of iterables
-#
+#
setup = common_setup + """
iterables = [tm.makeStringIndex(10000), xrange(20)]
@@ -130,3 +130,14 @@
Benchmark("MultiIndex.from_product([level1, level2]).values", setup,
name='multiindex_with_datetime_level',
start_date=datetime(2014, 10, 11))
+
+#----------------------------------------------------------------------
+# repr
+
+setup = common_setup + """
+dr = pd.date_range('20000101', freq='D', periods=100000)
+"""
+
+datetime_index_repr = \
+ Benchmark("dr._is_dates_only", setup,
+ start_date=datetime(2012, 1, 11))
| closes #8556
low hanging fruit (and now is pretty scale independent).
```
In [1]: dr = pd.date_range('20000101', freq='D', periods=100000)
In [2]: %timeit dr._is_dates_only
10000000 loops, best of 3: 87.6 ns per loop
In [3]: pd.__version__
Out[3]: '0.15.0rc1-38-g857042f'
```
I do recall this slipping in sometime maybe in 0.14.0 was the changing in how the default display would be handled for dates with and w/o times.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8557 | 2014-10-15T00:56:51Z | 2014-10-15T01:24:00Z | 2014-10-15T01:24:00Z | 2014-10-15T01:24:00Z |
Added footer to read_html | diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt
index 6688f106f922e..f76be6c7f5ab1 100644
--- a/doc/source/whatsnew/v0.15.2.txt
+++ b/doc/source/whatsnew/v0.15.2.txt
@@ -66,6 +66,7 @@ Enhancements
- Added support for ``utcfromtimestamp()``, ``fromtimestamp()``, and ``combine()`` on `Timestamp` class (:issue:`5351`).
- Added Google Analytics (`pandas.io.ga`) basic documentation (:issue:`8835`). See :ref:`here<remote_data.ga>`.
- Added flag ``order_categoricals`` to ``StataReader`` and ``read_stata`` to select whether to order imported categorical data (:issue:`8836`). See :ref:`here <io.stata-categorical>` for more information on importing categorical variables from Stata data files.
+- Added ability to read table footer to read_html (:issue:`8552`)
.. _whatsnew_0152.performance:
diff --git a/pandas/io/html.py b/pandas/io/html.py
index 7ef1e2d2df374..13318203bec67 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -577,7 +577,7 @@ def _parse_raw_thead(self, table):
table.xpath(expr)]
def _parse_raw_tfoot(self, table):
- expr = './/tfoot//th'
+ expr = './/tfoot//th|//tfoot//td'
return [_remove_whitespace(x.text_content()) for x in
table.xpath(expr)]
@@ -594,7 +594,7 @@ def _expand_elements(body):
def _data_to_frame(data, header, index_col, skiprows, infer_types,
parse_dates, tupleize_cols, thousands):
- head, body, _ = data # _ is footer which is rarely used: ignore for now
+ head, body, foot = data
if head:
body = [head] + body
@@ -602,6 +602,9 @@ def _data_to_frame(data, header, index_col, skiprows, infer_types,
if header is None: # special case when a table has <th> elements
header = 0
+ if foot:
+ body += [foot]
+
# fill out elements of body that are "ragged"
_expand_elements(body)
diff --git a/pandas/io/tests/test_html.py b/pandas/io/tests/test_html.py
index 748a008ae2c4b..c162bd7c50f5a 100644
--- a/pandas/io/tests/test_html.py
+++ b/pandas/io/tests/test_html.py
@@ -426,6 +426,38 @@ def test_empty_tables(self):
res1 = self.read_html(StringIO(data1))
res2 = self.read_html(StringIO(data2))
assert_framelist_equal(res1, res2)
+
+ def test_tfoot_read(self):
+ """
+ Make sure that read_html reads tfoot, containing td or th.
+ Ignores empty tfoot
+ """
+ data_template = '''<table>
+ <thead>
+ <tr>
+ <th>A</th>
+ <th>B</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>bodyA</td>
+ <td>bodyB</td>
+ </tr>
+ </tbody>
+ <tfoot>
+ {footer}
+ </tfoot>
+ </table>'''
+
+ data1 = data_template.format(footer = "")
+ data2 = data_template.format(footer ="<tr><td>footA</td><th>footB</th></tr>")
+
+ d1 = {'A': ['bodyA'], 'B': ['bodyB']}
+ d2 = {'A': ['bodyA', 'footA'], 'B': ['bodyB', 'footB']}
+
+ tm.assert_frame_equal(self.read_html(data1)[0], DataFrame(d1))
+ tm.assert_frame_equal(self.read_html(data2)[0], DataFrame(d2))
def test_countries_municipalities(self):
# GH5048
| read_html neglected table footers. Although rare, some sites use the footer for data. First time pull request so hopefully not messed up.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8552 | 2014-10-13T22:17:09Z | 2014-12-06T17:09:37Z | 2014-12-06T17:09:37Z | 2014-12-06T21:13:56Z |
ENH: Add ISO3 ctry codes and error arg. Fix tests, warn/exception logic #8482 | diff --git a/doc/source/remote_data.rst b/doc/source/remote_data.rst
index 33db9de48d9e7..bba3db86d837c 100644
--- a/doc/source/remote_data.rst
+++ b/doc/source/remote_data.rst
@@ -143,6 +143,12 @@ World Bank
`World Bank's World Development Indicators <http://data.worldbank.org>`__
by using the ``wb`` I/O functions.
+Indicators
+~~~~~~~~~~
+
+Either from exploring the World Bank site, or using the search function included,
+every world bank indicator is accessible.
+
For example, if you wanted to compare the Gross Domestic Products per capita in
constant dollars in North America, you would use the ``search`` function:
@@ -254,3 +260,56 @@ populations in rich countries tend to use cellphones at a higher rate:
Skew: -2.314 Prob(JB): 1.35e-26
Kurtosis: 11.077 Cond. No. 45.8
==============================================================================
+
+Country Codes
+~~~~~~~~~~~~~
+
+.. versionadded:: 0.15.1
+
+The ``country`` argument accepts a string or list of mixed
+`two <http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2>`__ or `three <http://en.wikipedia.org/wiki/ISO_3166-1_alpha-3>`__ character
+ISO country codes, as well as dynamic `World Bank exceptions <http://data.worldbank.org/node/18>`__ to the ISO standards.
+
+For a list of the the hard-coded country codes (used solely for error handling logic) see ``pandas.io.wb.country_codes``.
+
+Problematic Country Codes & Indicators
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. note::
+
+ The World Bank's country list and indicators are dynamic. As of 0.15.1,
+ :func:`wb.download()` is more flexible. To achieve this, the warning
+ and exception logic changed.
+
+The world bank converts some country codes,
+in their response, which makes error checking by pandas difficult.
+Retired indicators still persist in the search.
+
+Given the new flexibility of 0.15.1, improved error handling by the user
+may be necessary for fringe cases.
+
+To help identify issues:
+
+There are at least 4 kinds of country codes:
+
+1. Standard (2/3 digit ISO) - returns data, will warn and error properly.
+2. Non-standard (WB Exceptions) - returns data, but will falsely warn.
+3. Blank - silently missing from the response.
+4. Bad - causes the entire response from WB to fail, always exception inducing.
+
+There are at least 3 kinds of indicators:
+
+1. Current - Returns data.
+2. Retired - Appears in search results, yet won't return data.
+3. Bad - Will not return data.
+
+Use the ``errors`` argument to control warnings and exceptions. Setting
+errors to ignore or warn, won't stop failed responses. (ie, 100% bad
+indicators, or a single "bad" (#4 above) country code).
+
+See docstrings for more info.
+
+
+
+
+
diff --git a/doc/source/whatsnew/v0.15.1.txt b/doc/source/whatsnew/v0.15.1.txt
index 7b3aaa00e7ea9..4901c68f8fd23 100644
--- a/doc/source/whatsnew/v0.15.1.txt
+++ b/doc/source/whatsnew/v0.15.1.txt
@@ -19,18 +19,17 @@ users upgrade to this version.
API changes
~~~~~~~~~~~
-
-
+
.. _whatsnew_0151.enhancements:
Enhancements
~~~~~~~~~~~~
- Added option to select columns when importing Stata files (:issue:`7935`)
-
- Qualify memory usage in ``DataFrame.info()`` by adding ``+`` if it is a lower bound (:issue:`8578`)
-
-
+- Added support for 3-character ISO and non-standard country codes in :func:``io.wb.download()`` (:issue:`8482`)
+- :ref:`World Bank data requests <remote_data.wb>` now raise Warnings and ValueErrors based on an ``errors`` argument, as well as a list of hard-coded country codes and the World Bank's JSON response. In prior versions, the error messages didn't look at the World Bank's JSON response. Problem-inducing input were simply dropped prior to the request. The issue was that many good countries were cropped in the hard-coded approach. All countries will work now, but some bad countries will raise exceptions because some edge cases break the entire response.
+
.. _whatsnew_0151.performance:
Performance
@@ -41,8 +40,7 @@ Performance
Experimental
~~~~~~~~~~~~
-
-
+
.. _whatsnew_0151.bug_fixes:
Bug Fixes
diff --git a/pandas/io/tests/test_wb.py b/pandas/io/tests/test_wb.py
index 7c86f582dae1a..f0caf263ffd87 100644
--- a/pandas/io/tests/test_wb.py
+++ b/pandas/io/tests/test_wb.py
@@ -14,19 +14,15 @@ class TestWB(tm.TestCase):
@slow
@network
def test_wdi_search(self):
- raise nose.SkipTest
-
- expected = {u('id'): {2634: u('GDPPCKD'),
- 4649: u('NY.GDP.PCAP.KD'),
- 4651: u('NY.GDP.PCAP.KN'),
- 4653: u('NY.GDP.PCAP.PP.KD')},
- u('name'): {2634: u('GDP per Capita, constant US$, '
- 'millions'),
- 4649: u('GDP per capita (constant 2000 US$)'),
- 4651: u('GDP per capita (constant LCU)'),
- 4653: u('GDP per capita, PPP (constant 2005 '
+
+ expected = {u('id'): {6716: u('NY.GDP.PCAP.KD'),
+ 6718: u('NY.GDP.PCAP.KN'),
+ 6720: u('NY.GDP.PCAP.PP.KD')},
+ u('name'): {6716: u('GDP per capita (constant 2005 US$)'),
+ 6718: u('GDP per capita (constant LCU)'),
+ 6720: u('GDP per capita, PPP (constant 2011 '
'international $)')}}
- result = search('gdp.*capita.*constant').ix[:, :2]
+ result = search('gdp.*capita.*constant').loc[6716:,['id','name']]
expected = pandas.DataFrame(expected)
expected.index = result.index
assert_frame_equal(result, expected)
@@ -34,22 +30,93 @@ def test_wdi_search(self):
@slow
@network
def test_wdi_download(self):
- raise nose.SkipTest
- expected = {'GDPPCKN': {(u('United States'), u('2003')): u('40800.0735367688'), (u('Canada'), u('2004')): u('37857.1261134552'), (u('United States'), u('2005')): u('42714.8594790102'), (u('Canada'), u('2003')): u('37081.4575704003'), (u('United States'), u('2004')): u('41826.1728310667'), (u('Mexico'), u('2003')): u('72720.0691255285'), (u('Mexico'), u('2004')): u('74751.6003347038'), (u('Mexico'), u('2005')): u('76200.2154469437'), (u('Canada'), u('2005')): u('38617.4563629611')}, 'GDPPCKD': {(u('United States'), u('2003')): u('40800.0735367688'), (u('Canada'), u('2004')): u('34397.055116118'), (u('United States'), u('2005')): u('42714.8594790102'), (u('Canada'), u('2003')): u('33692.2812368928'), (u('United States'), u('2004')): u('41826.1728310667'), (u('Mexico'), u('2003')): u('7608.43848670658'), (u('Mexico'), u('2004')): u('7820.99026814334'), (u('Mexico'), u('2005')): u('7972.55364129367'), (u('Canada'), u('2005')): u('35087.8925933298')}}
+ # Test a bad indicator with double (US), triple (USA),
+ # standard (CA, MX), non standard (KSV),
+ # duplicated (US, US, USA), and unknown (BLA) country codes
+
+ # ...but NOT a crash inducing country code (World bank strips pandas
+ # users of the luxury of laziness, because they create their
+ # own exceptions, and don't clean up legacy country codes.
+ # ...but NOT a retired indicator (User should want it to error.)
+
+ cntry_codes = ['CA', 'MX', 'USA', 'US', 'US', 'KSV', 'BLA']
+ inds = ['NY.GDP.PCAP.CD','BAD.INDICATOR']
+
+ expected = {'NY.GDP.PCAP.CD': {('Canada', '2003'): 28026.006013044702, ('Mexico', '2003'): 6601.0420648056606, ('Canada', '2004'): 31829.522562759001, ('Kosovo', '2003'): 1969.56271307405, ('Mexico', '2004'): 7042.0247834044303, ('United States', '2004'): 41928.886136479705, ('United States', '2003'): 39682.472247320402, ('Kosovo', '2004'): 2135.3328465238301}}
expected = pandas.DataFrame(expected)
- result = download(country=['CA', 'MX', 'US', 'junk'], indicator=['GDPPCKD',
- 'GDPPCKN', 'junk'], start=2003, end=2005)
+ expected.sort(inplace=True)
+ result = download(country=cntry_codes, indicator=inds,
+ start=2003, end=2004, errors='ignore')
+ result.sort(inplace=True)
expected.index = result.index
assert_frame_equal(result, pandas.DataFrame(expected))
+ @slow
+ @network
+ def test_wdi_download_w_retired_indicator(self):
+
+ cntry_codes = ['CA', 'MX', 'US']
+ # Despite showing up in the search feature, and being listed online,
+ # the api calls to GDPPCKD don't work in their own query builder, nor
+ # pandas module. GDPPCKD used to be a common symbol.
+ # This test is written to ensure that error messages to pandas users
+ # continue to make sense, rather than a user getting some missing
+ # key error, cause their JSON message format changed. If
+ # World bank ever finishes the deprecation of this symbol,
+ # this nose test should still pass.
+
+ inds = ['GDPPCKD']
+
+ try:
+ result = download(country=cntry_codes, indicator=inds,
+ start=2003, end=2004, errors='ignore')
+ # If for some reason result actually ever has data, it's cause WB
+ # fixed the issue with this ticker. Find another bad one.
+ except ValueError as e:
+ error_raised = True
+ error_msg = e.args[0]
+
+ self.assertTrue(error_raised)
+ self.assertTrue("No indicators returned data." in error_msg)
+
+ # if it ever gets here, it means WB unretired the indicator.
+ # even if they dropped it completely, it would still get caught above
+ # or the WB API changed somehow in a really unexpected way.
+ if len(result) > 0:
+ raise nose.SkipTest
+
+
+
+ @slow
+ @network
+ def test_wdi_download_w_crash_inducing_countrycode(self):
+
+ cntry_codes = ['CA', 'MX', 'US', 'XXX']
+ inds = ['NY.GDP.PCAP.CD']
+
+ try:
+ result = download(country=cntry_codes, indicator=inds,
+ start=2003, end=2004, errors='ignore')
+ except ValueError as e:
+ error_raised = True
+ error_msg = e.args[0]
+
+ self.assertTrue(error_raised)
+ self.assertTrue("No indicators returned data." in error_msg)
+
+ # if it ever gets here, it means the country code XXX got used by WB
+ # or the WB API changed somehow in a really unexpected way.
+ if len(result) > 0:
+ raise nose.SkipTest
+
@slow
@network
def test_wdi_get_countries(self):
result = get_countries()
self.assertTrue('Zimbabwe' in list(result['name']))
-
+ self.assertTrue(len(result) > 100)
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
- exit=False)
+ exit=False)
\ No newline at end of file
diff --git a/pandas/io/wb.py b/pandas/io/wb.py
index d815bb19ec8b8..7a9443c4b9ac6 100644
--- a/pandas/io/wb.py
+++ b/pandas/io/wb.py
@@ -1,3 +1,5 @@
+# -*- coding: utf-8 -*-
+
from __future__ import print_function
from pandas.compat import map, reduce, range, lrange
@@ -5,10 +7,74 @@
from pandas.io import json
import pandas
import numpy as np
+import warnings
+
+# This list of country codes was pulled from wikipedia during October 2014.
+# While some exceptions do exist, it is the best proxy for countries supported
+# by World Bank. It is an aggregation of the 2-digit ISO 3166-1 alpha-2, and
+# 3-digit ISO 3166-1 alpha-3, codes, with 'all', 'ALL', and 'All' appended ot
+# the end.
+country_codes = ['AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', \
+ 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', \
+ 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', \
+ 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', \
+ 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', \
+ 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', \
+ 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', \
+ 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', \
+ 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', \
+ 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', \
+ 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', \
+ 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', \
+ 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', \
+ 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', \
+ 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', \
+ 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', \
+ 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', \
+ 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', \
+ 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', \
+ 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', \
+ 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', \
+ 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', \
+ 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', \
+ 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', \
+ 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW', \
+ 'ABW', 'AFG', 'AGO', 'AIA', 'ALA', 'ALB', 'AND', 'ARE', \
+ 'ARG', 'ARM', 'ASM', 'ATA', 'ATF', 'ATG', 'AUS', 'AUT', \
+ 'AZE', 'BDI', 'BEL', 'BEN', 'BES', 'BFA', 'BGD', 'BGR', \
+ 'BHR', 'BHS', 'BIH', 'BLM', 'BLR', 'BLZ', 'BMU', 'BOL', \
+ 'BRA', 'BRB', 'BRN', 'BTN', 'BVT', 'BWA', 'CAF', 'CAN', \
+ 'CCK', 'CHE', 'CHL', 'CHN', 'CIV', 'CMR', 'COD', 'COG', \
+ 'COK', 'COL', 'COM', 'CPV', 'CRI', 'CUB', 'CUW', 'CXR', \
+ 'CYM', 'CYP', 'CZE', 'DEU', 'DJI', 'DMA', 'DNK', 'DOM', \
+ 'DZA', 'ECU', 'EGY', 'ERI', 'ESH', 'ESP', 'EST', 'ETH', \
+ 'FIN', 'FJI', 'FLK', 'FRA', 'FRO', 'FSM', 'GAB', 'GBR', \
+ 'GEO', 'GGY', 'GHA', 'GIB', 'GIN', 'GLP', 'GMB', 'GNB', \
+ 'GNQ', 'GRC', 'GRD', 'GRL', 'GTM', 'GUF', 'GUM', 'GUY', \
+ 'HKG', 'HMD', 'HND', 'HRV', 'HTI', 'HUN', 'IDN', 'IMN', \
+ 'IND', 'IOT', 'IRL', 'IRN', 'IRQ', 'ISL', 'ISR', 'ITA', \
+ 'JAM', 'JEY', 'JOR', 'JPN', 'KAZ', 'KEN', 'KGZ', 'KHM', \
+ 'KIR', 'KNA', 'KOR', 'KWT', 'LAO', 'LBN', 'LBR', 'LBY', \
+ 'LCA', 'LIE', 'LKA', 'LSO', 'LTU', 'LUX', 'LVA', 'MAC', \
+ 'MAF', 'MAR', 'MCO', 'MDA', 'MDG', 'MDV', 'MEX', 'MHL', \
+ 'MKD', 'MLI', 'MLT', 'MMR', 'MNE', 'MNG', 'MNP', 'MOZ', \
+ 'MRT', 'MSR', 'MTQ', 'MUS', 'MWI', 'MYS', 'MYT', 'NAM', \
+ 'NCL', 'NER', 'NFK', 'NGA', 'NIC', 'NIU', 'NLD', 'NOR', \
+ 'NPL', 'NRU', 'NZL', 'OMN', 'PAK', 'PAN', 'PCN', 'PER', \
+ 'PHL', 'PLW', 'PNG', 'POL', 'PRI', 'PRK', 'PRT', 'PRY', \
+ 'PSE', 'PYF', 'QAT', 'REU', 'ROU', 'RUS', 'RWA', 'SAU', \
+ 'SDN', 'SEN', 'SGP', 'SGS', 'SHN', 'SJM', 'SLB', 'SLE', \
+ 'SLV', 'SMR', 'SOM', 'SPM', 'SRB', 'SSD', 'STP', 'SUR', \
+ 'SVK', 'SVN', 'SWE', 'SWZ', 'SXM', 'SYC', 'SYR', 'TCA', \
+ 'TCD', 'TGO', 'THA', 'TJK', 'TKL', 'TKM', 'TLS', 'TON', \
+ 'TTO', 'TUN', 'TUR', 'TUV', 'TWN', 'TZA', 'UGA', 'UKR', \
+ 'UMI', 'URY', 'USA', 'UZB', 'VAT', 'VCT', 'VEN', 'VGB', \
+ 'VIR', 'VNM', 'VUT', 'WLF', 'WSM', 'YEM', 'ZAF', 'ZMB', \
+ 'ZWE', 'all', 'ALL', 'All']
-def download(country=['MX', 'CA', 'US'], indicator=['GDPPCKD', 'GDPPCKN'],
- start=2003, end=2005):
+def download(country=['MX', 'CA', 'US'], indicator=['NY.GDP.MKTP.CD', 'NY.GNS.ICTR.ZS'],
+ start=2003, end=2005,errors='warn'):
"""
Download data series from the World Bank's World Development Indicators
@@ -17,91 +83,133 @@ def download(country=['MX', 'CA', 'US'], indicator=['GDPPCKD', 'GDPPCKN'],
indicator: string or list of strings
taken from the ``id`` field in ``WDIsearch()``
+
country: string or list of strings.
``all`` downloads data for all countries
- ISO-2 character codes select individual countries (e.g.``US``,``CA``)
+ 2 or 3 character ISO country codes select individual
+ countries (e.g.``US``,``CA``) or (e.g.``USA``,``CAN``). The codes
+ can be mixed.
+
+ The two ISO lists of countries, provided by wikipedia, are hardcoded
+ into pandas as of 11/10/2014.
+
start: int
First year of the data series
+
end: int
Last year of the data series (inclusive)
-
+
+ errors: str {'ignore', 'warn', 'raise'}, default 'warn'
+ Country codes are validated against a hardcoded list. This controls
+ the outcome of that validation, and attempts to also apply
+ to the results from world bank.
+
+ errors='raise', will raise a ValueError on a bad country code.
+
Returns
-------
- ``pandas`` DataFrame with columns: country, iso2c, year, indicator value.
+ ``pandas`` DataFrame with columns: country, iso_code, year,
+ indicator value.
+
"""
- # Are ISO-2 country codes valid?
- valid_countries = [
- "AG", "AL", "AM", "AO", "AR", "AT", "AU", "AZ", "BB", "BD", "BE", "BF",
- "BG", "BH", "BI", "BJ", "BO", "BR", "BS", "BW", "BY", "BZ", "CA", "CD",
- "CF", "CG", "CH", "CI", "CL", "CM", "CN", "CO", "CR", "CV", "CY", "CZ",
- "DE", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "ER", "ES", "ET", "FI",
- "FJ", "FR", "GA", "GB", "GE", "GH", "GM", "GN", "GQ", "GR", "GT", "GW",
- "GY", "HK", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IN", "IR", "IS",
- "IT", "JM", "JO", "JP", "KE", "KG", "KH", "KM", "KR", "KW", "KZ", "LA",
- "LB", "LC", "LK", "LS", "LT", "LU", "LV", "MA", "MD", "MG", "MK", "ML",
- "MN", "MR", "MU", "MW", "MX", "MY", "MZ", "NA", "NE", "NG", "NI", "NL",
- "NO", "NP", "NZ", "OM", "PA", "PE", "PG", "PH", "PK", "PL", "PT", "PY",
- "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SI", "SK", "SL",
- "SN", "SR", "SV", "SY", "SZ", "TD", "TG", "TH", "TN", "TR", "TT", "TW",
- "TZ", "UA", "UG", "US", "UY", "UZ", "VC", "VE", "VN", "VU", "YE", "ZA",
- "ZM", "ZW", "all"
- ]
if type(country) == str:
country = [country]
- bad_countries = np.setdiff1d(country, valid_countries)
- country = np.intersect1d(country, valid_countries)
- country = ';'.join(country)
+
+ bad_countries = np.setdiff1d(country, country_codes)
+
+ # Validate the input
+ if len(bad_countries) > 0:
+ tmp = ", ".join(bad_countries)
+ if errors == 'raise':
+ raise ValueError("Invalid Country Code(s): %s" % tmp)
+ if errors == 'warn':
+ warnings.warn('Non-standard ISO country codes: %s' % tmp)
+
# Work with a list of indicators
if type(indicator) == str:
indicator = [indicator]
+
# Download
data = []
- bad_indicators = []
+ bad_indicators = {}
for ind in indicator:
- try:
- tmp = _get_data(ind, country, start, end)
- tmp.columns = ['country', 'iso2c', 'year', ind]
- data.append(tmp)
- except:
- bad_indicators.append(ind)
- # Warn
- if len(bad_indicators) > 0:
- print('Failed to obtain indicator(s): %s' % '; '.join(bad_indicators))
- print('The data may still be available for download at '
- 'http://data.worldbank.org')
- if len(bad_countries) > 0:
- print('Invalid ISO-2 codes: %s' % ' '.join(bad_countries))
- # Merge WDI series
+ one_indicator_data,msg = _get_data(ind, country, start, end)
+ if msg == "Success":
+ data.append(one_indicator_data)
+ else:
+ bad_indicators[ind] = msg
+
+ if len(bad_indicators.keys()) > 0:
+ bad_ind_msgs = [i + " : " + m for i,m in bad_indicators.items()]
+ bad_ind_msgs = "\n\n".join(bad_ind_msgs)
+ bad_ind_msgs = "\n\nInvalid Indicators:\n\n%s" % bad_ind_msgs
+ if errors == 'raise':
+ raise ValueError(bad_ind_msgs)
+ if errors == 'warn':
+ warnings.warn(bad_ind_msgs)
+
+ # Confirm we actually got some data, and build Dataframe
if len(data) > 0:
out = reduce(lambda x, y: x.merge(y, how='outer'), data)
- # Clean
- out = out.drop('iso2c', axis=1)
+ out = out.drop('iso_code', axis=1)
out = out.set_index(['country', 'year'])
out = out.convert_objects(convert_numeric=True)
return out
-
+ else:
+ msg = "No indicators returned data."
+ if errors == 'ignore':
+ msg += " Set errors='warn' for more information."
+ raise ValueError(msg)
def _get_data(indicator="NY.GNS.ICTR.GN.ZS", country='US',
start=2002, end=2005):
+
+ if type(country) == str:
+ country = [country]
+
+ countries = ';'.join(country)
+
# Build URL for api call
- url = ("http://api.worldbank.org/countries/" + country + "/indicators/" +
+ url = ("http://api.worldbank.org/countries/" + countries + "/indicators/" +
indicator + "?date=" + str(start) + ":" + str(end) +
"&per_page=25000&format=json")
+
# Download
with urlopen(url) as response:
data = response.read()
+
+ # Check to see if there is a possible problem
+ possible_message = json.loads(data)[0]
+ if 'message' in possible_message.keys():
+ msg = possible_message['message'][0]
+ try:
+ msg = msg['key'].split() + ["\n "] + msg['value'].split()
+ wb_err = ' '.join(msg)
+ except:
+ wb_err = ""
+ if 'key' in msg.keys():
+ wb_err = msg['key'] + "\n "
+ if 'value' in msg.keys():
+ wb_err += msg['value']
+ error_msg = "Problem with a World Bank Query \n %s"
+ return None, error_msg % wb_err
+
+ if 'total' in possible_message.keys():
+ if possible_message['total'] == 0:
+ return None, "No results from world bank."
+
# Parse JSON file
data = json.loads(data)[1]
country = [x['country']['value'] for x in data]
- iso2c = [x['country']['id'] for x in data]
+ iso_code = [x['country']['id'] for x in data]
year = [x['date'] for x in data]
value = [x['value'] for x in data]
# Prepare output
- out = pandas.DataFrame([country, iso2c, year, value]).T
- return out
-
+ out = pandas.DataFrame([country, iso_code, year, value]).T
+ out.columns = ['country', 'iso_code', 'year', indicator]
+ return out,"Success"
def get_countries():
'''Query information about countries
@@ -118,7 +226,6 @@ def get_countries():
data = data.rename(columns={'id': 'iso3c', 'iso2Code': 'iso2c'})
return data
-
def get_indicators():
'''Download information about all World Bank data series
'''
@@ -146,7 +253,6 @@ def get_value(x):
data.index = pandas.Index(lrange(data.shape[0]))
return data
-
_cached_series = None
@@ -190,3 +296,4 @@ def search(string='gdp.*capi', field='name', case=False):
idx = data.str.contains(string, case=case)
out = _cached_series.ix[idx].dropna()
return out
+
| This PR adds ISO 3-digit country codes, support for World Bank Country Code exceptions, by changing the error handling and warning logic and introducing an `error` argument which toggles between ignore/warn/raise . Validation no longer filters bad country codes, prior to submitting the API request. Instead, it attempts to catch errors in the WB response - which is a very hairy thing. See notes added in remote_data.tst for issues.
During this PR, we attempted to clean up the JSON response, and make the module as simple as possible, without restricting the user. In the end, it proved somewhat awkward, but the solution is a good one given the constraints of the WB API.
closes #8482 .
Updated right before merging to remove noise, and provide a summary.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8551 | 2014-10-13T21:58:19Z | 2014-10-28T00:25:36Z | 2014-10-28T00:25:36Z | 2015-02-09T00:43:38Z |
ENH: Move any/all to NDFrame, support additional arguments for Series. GH8302 | diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt
index 4bcbcb82e7c83..52b0391534313 100644
--- a/doc/source/whatsnew/v0.15.2.txt
+++ b/doc/source/whatsnew/v0.15.2.txt
@@ -22,6 +22,20 @@ API changes
- Bug in concat of Series with ``category`` dtype which were coercing to ``object``. (:issue:`8641`)
+- ``Series.all`` and ``Series.any`` now support the ``level`` and ``skipna`` parameters. ``Series.all``, ``Series.any``, ``Index.all``, and ``Index.any`` no longer support the ``out`` and ``keepdims`` parameters, which existed for compatibility with ndarray. Various index types no longer support the ``all`` and ``any`` aggregation functions. (:issue:`8302`):
+
+ .. ipython:: python
+
+ s = pd.Series([False, True, False], index=[0, 0, 1])
+ s.any(level=0)
+
+- ``Panel`` now supports the ``all`` and ``any`` aggregation functions. (:issue:`8302`):
+
+ .. ipython:: python
+
+ p = pd.Panel(np.random.rand(2, 5, 4) > 0.1)
+ p.all()
+
.. _whatsnew_0152.enhancements:
Enhancements
@@ -44,4 +58,4 @@ Experimental
Bug Fixes
~~~~~~~~~
- Bug in ``groupby`` signatures that didn't include *args or **kwargs (:issue:`8733`).
-- ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo (:issue:`8761`).
\ No newline at end of file
+- ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo (:issue:`8761`).
diff --git a/pandas/core/base.py b/pandas/core/base.py
index fba83be6fcadf..f648af85b68c5 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -268,18 +268,6 @@ def __unicode__(self):
quote_strings=True)
return "%s(%s, dtype='%s')" % (type(self).__name__, prepr, self.dtype)
-def _unbox(func):
- @Appender(func.__doc__)
- def f(self, *args, **kwargs):
- result = func(self.values, *args, **kwargs)
- from pandas.core.index import Index
- if isinstance(result, (np.ndarray, com.ABCSeries, Index)) and result.ndim == 0:
- # return NumPy type
- return result.dtype.type(result.item())
- else: # pragma: no cover
- return result
- f.__name__ = func.__name__
- return f
class IndexOpsMixin(object):
""" common ops mixin to support a unified inteface / docs for Series / Index """
@@ -528,12 +516,6 @@ def duplicated(self, take_last=False):
from pandas.core.index import Index
return Index(duplicated)
- #----------------------------------------------------------------------
- # unbox reductions
-
- all = _unbox(np.ndarray.all)
- any = _unbox(np.ndarray.any)
-
#----------------------------------------------------------------------
# abstracts
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 4ce9cc5804264..0ea53920ffe3c 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4133,68 +4133,6 @@ def _count_level(self, level, axis=0, numeric_only=False):
else:
return result
- def any(self, axis=None, bool_only=None, skipna=True, level=None,
- **kwargs):
- """
- Return whether any element is True over requested axis.
- %(na_action)s
-
- Parameters
- ----------
- axis : {0, 1}
- 0 for row-wise, 1 for column-wise
- skipna : boolean, default True
- Exclude NA/null values. If an entire row/column is NA, the result
- will be NA
- level : int or level name, default None
- If the axis is a MultiIndex (hierarchical), count along a
- particular level, collapsing into a DataFrame
- bool_only : boolean, default None
- Only include boolean data.
-
- Returns
- -------
- any : Series (or DataFrame if level specified)
- """
- if axis is None:
- axis = self._stat_axis_number
- if level is not None:
- return self._agg_by_level('any', axis=axis, level=level,
- skipna=skipna)
- return self._reduce(nanops.nanany, 'any', axis=axis, skipna=skipna,
- numeric_only=bool_only, filter_type='bool')
-
- def all(self, axis=None, bool_only=None, skipna=True, level=None,
- **kwargs):
- """
- Return whether all elements are True over requested axis.
- %(na_action)s
-
- Parameters
- ----------
- axis : {0, 1}
- 0 for row-wise, 1 for column-wise
- skipna : boolean, default True
- Exclude NA/null values. If an entire row/column is NA, the result
- will be NA
- level : int or level name, default None
- If the axis is a MultiIndex (hierarchical), count along a
- particular level, collapsing into a DataFrame
- bool_only : boolean, default None
- Only include boolean data.
-
- Returns
- -------
- any : Series (or DataFrame if level specified)
- """
- if axis is None:
- axis = self._stat_axis_number
- if level is not None:
- return self._agg_by_level('all', axis=axis, level=level,
- skipna=skipna)
- return self._reduce(nanops.nanall, 'all', axis=axis, skipna=skipna,
- numeric_only=bool_only, filter_type='bool')
-
def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
filter_type=None, **kwds):
axis = self._get_axis_number(axis)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 89178ba2d9dcc..89c6e5836022e 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3888,6 +3888,7 @@ def _add_numeric_operations(cls):
])
name = (cls._constructor_sliced.__name__
if cls._AXIS_LEN > 1 else 'scalar')
+
_num_doc = """
%(desc)s
@@ -3905,6 +3906,27 @@ def _add_numeric_operations(cls):
Include only float, int, boolean data. If None, will attempt to use
everything, then use only numeric data
+Returns
+-------
+%(outname)s : """ + name + " or " + cls.__name__ + " (if level specified)\n"
+
+ _bool_doc = """
+
+%(desc)s
+
+Parameters
+----------
+axis : """ + axis_descr + """
+skipna : boolean, default True
+ Exclude NA/null values. If an entire row/column is NA, the result
+ will be NA
+level : int or level name, default None
+ If the axis is a MultiIndex (hierarchical), count along a
+ particular level, collapsing into a """ + name + """
+bool_only : boolean, default None
+ Include only boolean data. If None, will attempt to use everything,
+ then use only boolean data
+
Returns
-------
%(outname)s : """ + name + " or " + cls.__name__ + " (if level specified)\n"
@@ -3971,6 +3993,36 @@ def stat_func(self, axis=None, skipna=None, level=None,
want the *index* of the minimum, use ``idxmin``. This is the
equivalent of the ``numpy.ndarray`` method ``argmin``.""", nanops.nanmin)
+ def _make_logical_function(name, desc, f):
+
+ @Substitution(outname=name, desc=desc)
+ @Appender(_bool_doc)
+ def logical_func(self, axis=None, bool_only=None, skipna=None,
+ level=None, **kwargs):
+ if skipna is None:
+ skipna = True
+ if axis is None:
+ axis = self._stat_axis_number
+ if level is not None:
+ if bool_only is not None:
+ raise NotImplementedError(
+ "Option bool_only is not implemented with option "
+ "level.")
+ return self._agg_by_level(name, axis=axis, level=level,
+ skipna=skipna)
+ return self._reduce(f, axis=axis, skipna=skipna,
+ numeric_only=bool_only, filter_type='bool',
+ name=name)
+ logical_func.__name__ = name
+ return logical_func
+
+ cls.any = _make_logical_function(
+ 'any', 'Return whether any element is True over requested axis',
+ nanops.nanany)
+ cls.all = _make_logical_function(
+ 'all', 'Return whether all elements are True over requested axis',
+ nanops.nanall)
+
@Substitution(outname='mad',
desc="Return the mean absolute deviation of the values "
"for the requested axis")
diff --git a/pandas/core/index.py b/pandas/core/index.py
index a6907c3f8b5f2..02877072b8c74 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -14,7 +14,8 @@
import pandas.index as _index
from pandas.lib import Timestamp, Timedelta, is_datetime_array
from pandas.core.base import PandasObject, FrozenList, FrozenNDArray, IndexOpsMixin, _shared_docs
-from pandas.util.decorators import Appender, cache_readonly, deprecate
+from pandas.util.decorators import (Appender, Substitution, cache_readonly,
+ deprecate)
from pandas.core.common import isnull, array_equivalent
import pandas.core.common as com
from pandas.core.common import (_values_from_object, is_float, is_integer,
@@ -2088,12 +2089,13 @@ def _evaluate_with_datetime_like(self, other, op, opstr):
def _add_numeric_methods_disabled(cls):
""" add in numeric methods to disable """
- def _make_invalid_op(opstr):
+ def _make_invalid_op(name):
- def _invalid_op(self, other=None):
- raise TypeError("cannot perform {opstr} with this index type: {typ}".format(opstr=opstr,
- typ=type(self)))
- return _invalid_op
+ def invalid_op(self, other=None):
+ raise TypeError("cannot perform {name} with this index type: {typ}".format(name=name,
+ typ=type(self)))
+ invalid_op.__name__ = name
+ return invalid_op
cls.__mul__ = cls.__rmul__ = _make_invalid_op('__mul__')
cls.__floordiv__ = cls.__rfloordiv__ = _make_invalid_op('__floordiv__')
@@ -2178,8 +2180,62 @@ def _evaluate_numeric_unary(self):
cls.__abs__ = _make_evaluate_unary(lambda x: np.abs(x),'__abs__')
cls.__inv__ = _make_evaluate_unary(lambda x: -x,'__inv__')
+ @classmethod
+ def _add_logical_methods(cls):
+ """ add in logical methods """
+
+ _doc = """
+
+ %(desc)s
+
+ Parameters
+ ----------
+ All arguments to numpy.%(outname)s are accepted.
+
+ Returns
+ -------
+ %(outname)s : bool or array_like (if axis is specified)
+ A single element array_like may be converted to bool."""
+
+ def _make_logical_function(name, desc, f):
+
+ @Substitution(outname=name, desc=desc)
+ @Appender(_doc)
+ def logical_func(self, *args, **kwargs):
+ result = f(self.values)
+ if isinstance(result, (np.ndarray, com.ABCSeries, Index)) \
+ and result.ndim == 0:
+ # return NumPy type
+ return result.dtype.type(result.item())
+ else: # pragma: no cover
+ return result
+ logical_func.__name__ = name
+ return logical_func
+
+ cls.all = _make_logical_function(
+ 'all', 'Return whether all elements are True', np.all)
+ cls.any = _make_logical_function(
+ 'any', 'Return whether any element is True', np.any)
+
+ @classmethod
+ def _add_logical_methods_disabled(cls):
+ """ add in logical methods to disable """
+
+ def _make_invalid_op(name):
+
+ def invalid_op(self, other=None):
+ raise TypeError("cannot perform {name} with this index type: {typ}".format(name=name,
+ typ=type(self)))
+ invalid_op.__name__ = name
+ return invalid_op
+
+ cls.all = _make_invalid_op('all')
+ cls.any = _make_invalid_op('any')
+
Index._add_numeric_methods_disabled()
+Index._add_logical_methods()
+
class NumericIndex(Index):
"""
@@ -2291,7 +2347,11 @@ def equals(self, other):
def _wrap_joined_index(self, joined, other):
name = self.name if self.name == other.name else None
return Int64Index(joined, name=name)
+
+
Int64Index._add_numeric_methods()
+Int64Index._add_logical_methods()
+
class Float64Index(NumericIndex):
@@ -2483,7 +2543,10 @@ def isin(self, values, level=None):
self._validate_index_level(level)
return lib.ismember_nans(self._array_values(), value_set,
isnull(list(value_set)).any())
+
+
Float64Index._add_numeric_methods()
+Float64Index._add_logical_methods_disabled()
class MultiIndex(Index):
@@ -4436,7 +4499,11 @@ def isin(self, values, level=None):
return np.zeros(len(labs), dtype=np.bool_)
else:
return np.lib.arraysetops.in1d(labs, sought_labels)
+
+
MultiIndex._add_numeric_methods_disabled()
+MultiIndex._add_logical_methods_disabled()
+
# For utility purposes
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 8ab5c30c49f10..adb5e7d07fbe6 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -75,6 +75,15 @@ def test_numeric_compat(self):
"cannot perform __floordiv__",
lambda : 1 // idx)
+ def test_logical_compat(self):
+ idx = self.create_index()
+ tm.assertRaisesRegexp(TypeError,
+ 'cannot perform all',
+ lambda : idx.all())
+ tm.assertRaisesRegexp(TypeError,
+ 'cannot perform any',
+ lambda : idx.any())
+
def test_boolean_context_compat(self):
# boolean context compat
@@ -820,6 +829,11 @@ def test_take(self):
expected = self.dateIndex[indexer]
self.assertTrue(result.equals(expected))
+ def test_logical_compat(self):
+ idx = self.create_index()
+ self.assertEqual(idx.all(), idx.values.all())
+ self.assertEqual(idx.any(), idx.values.any())
+
def _check_method_works(self, method):
method(self.empty)
method(self.dateIndex)
@@ -1467,6 +1481,11 @@ def test_equals(self):
self.assertTrue(self.index.equals(same_values))
self.assertTrue(same_values.equals(self.index))
+ def test_logical_compat(self):
+ idx = self.create_index()
+ self.assertEqual(idx.all(), idx.values.all())
+ self.assertEqual(idx.any(), idx.values.any())
+
def test_identical(self):
i = Index(self.index.copy())
self.assertTrue(i.identical(self.index))
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 01d086f57718c..7f902827ba5db 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -9,6 +9,7 @@
from pandas import Series, DataFrame, Index, isnull, notnull, pivot, MultiIndex
from pandas.core.datetools import bday
+from pandas.core.nanops import nanall, nanany
from pandas.core.panel import Panel
from pandas.core.series import remove_na
import pandas.core.common as com
@@ -2102,6 +2103,24 @@ def test_update_raise(self):
np.testing.assert_raises(Exception, pan.update, *(pan,),
**{'raise_conflict': True})
+ def test_all_any(self):
+ self.assertTrue((self.panel.all(axis=0).values ==
+ nanall(self.panel, axis=0)).all())
+ self.assertTrue((self.panel.all(axis=1).values ==
+ nanall(self.panel, axis=1).T).all())
+ self.assertTrue((self.panel.all(axis=2).values ==
+ nanall(self.panel, axis=2).T).all())
+ self.assertTrue((self.panel.any(axis=0).values ==
+ nanany(self.panel, axis=0)).all())
+ self.assertTrue((self.panel.any(axis=1).values ==
+ nanany(self.panel, axis=1).T).all())
+ self.assertTrue((self.panel.any(axis=2).values ==
+ nanany(self.panel, axis=2).T).all())
+
+ def test_all_any_unhandled(self):
+ self.assertRaises(NotImplementedError, self.panel.all, bool_only=True)
+ self.assertRaises(NotImplementedError, self.panel.any, bool_only=True)
+
class TestLongPanel(tm.TestCase):
"""
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 9ecdcd2b12d75..c4c2eebacb0e9 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -2474,6 +2474,33 @@ def test_all_any(self):
self.assertFalse(bool_series.all())
self.assertTrue(bool_series.any())
+ # Alternative types, with implicit 'object' dtype.
+ s = Series(['abc', True])
+ self.assertEquals('abc', s.any()) # 'abc' || True => 'abc'
+
+ def test_all_any_params(self):
+ # Check skipna, with implicit 'object' dtype.
+ s1 = Series([np.nan, True])
+ s2 = Series([np.nan, False])
+ self.assertTrue(s1.all(skipna=False)) # nan && True => True
+ self.assertTrue(s1.all(skipna=True))
+ self.assertTrue(np.isnan(s2.any(skipna=False))) # nan || False => nan
+ self.assertFalse(s2.any(skipna=True))
+
+ # Check level.
+ s = pd.Series([False, False, True, True, False, True],
+ index=[0, 0, 1, 1, 2, 2])
+ assert_series_equal(s.all(level=0), Series([False, True, False]))
+ assert_series_equal(s.any(level=0), Series([False, True, True]))
+
+ # bool_only is not implemented with level option.
+ self.assertRaises(NotImplementedError, s.any, bool_only=True, level=0)
+ self.assertRaises(NotImplementedError, s.all, bool_only=True, level=0)
+
+ # bool_only is not implemented alone.
+ self.assertRaises(NotImplementedError, s.any, bool_only=True)
+ self.assertRaises(NotImplementedError, s.all, bool_only=True)
+
def test_op_method(self):
def check(series, other, check_reverse=False):
simple_ops = ['add', 'sub', 'mul', 'floordiv', 'truediv', 'pow']
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 52ab217cbffc6..bf99de902188f 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -1665,9 +1665,13 @@ def to_julian_date(self):
self.microsecond/3600.0/1e+6 +
self.nanosecond/3600.0/1e+9
)/24.0)
+
+
DatetimeIndex._add_numeric_methods_disabled()
+DatetimeIndex._add_logical_methods_disabled()
DatetimeIndex._add_datetimelike_methods()
+
def _generate_regular_range(start, end, periods, offset):
if isinstance(offset, Tick):
stride = offset.nanos
diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py
index 742d8651a4035..0b4ca5014e76b 100644
--- a/pandas/tseries/period.py
+++ b/pandas/tseries/period.py
@@ -1262,9 +1262,12 @@ def tz_localize(self, tz, infer_dst=False):
"""
raise NotImplementedError("Not yet implemented for PeriodIndex")
+
PeriodIndex._add_numeric_methods_disabled()
+PeriodIndex._add_logical_methods_disabled()
PeriodIndex._add_datetimelike_methods()
+
def _get_ordinal_range(start, end, periods, freq):
if com._count_not_none(start, end, periods) < 2:
raise ValueError('Must specify 2 of start, end, periods')
diff --git a/pandas/tseries/tdi.py b/pandas/tseries/tdi.py
index 5a041ed09fb27..0d99cd16d8c99 100644
--- a/pandas/tseries/tdi.py
+++ b/pandas/tseries/tdi.py
@@ -890,9 +890,12 @@ def delete(self, loc):
return TimedeltaIndex(new_tds, name=self.name, freq=freq)
+
TimedeltaIndex._add_numeric_methods()
+TimedeltaIndex._add_logical_methods_disabled()
TimedeltaIndex._add_datetimelike_methods()
+
def _is_convertible_to_index(other):
""" return a boolean whether I can attempt conversion to a TimedeltaIndex """
if isinstance(other, TimedeltaIndex):
| closes #8302
- Move any/all implementations from DataFrame to NDFrame, adding support for Series
- Special case single dimension case in NDFrame, to handle numpy.any/all specific arguments
- Add assorted NotImplementedErrors in cases where arguments are ignored (including in preexisting _reduce functions)
- Move the other any/all implementations from IndexOpsMixin to Index, outside of Series’ inheritance tree
| https://api.github.com/repos/pandas-dev/pandas/pulls/8550 | 2014-10-13T17:39:48Z | 2014-11-11T14:32:45Z | 2014-11-11T14:32:45Z | 2014-11-11T14:33:25Z |
PERF: Slowness in multi-level indexes with datetime levels (part 2) | diff --git a/pandas/core/index.py b/pandas/core/index.py
index 919018977cb80..c2c7e28a7a7f4 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -2937,11 +2937,16 @@ def values(self):
values = []
for lev, lab in zip(self.levels, self.labels):
- lev_values = lev.values
# Need to box timestamps, etc.
- if hasattr(lev, '_box_values'):
- lev_values = lev._box_values(lev_values)
- taken = com.take_1d(lev_values, lab)
+ box = hasattr(lev, '_box_values')
+ # Try to minimize boxing.
+ if box and len(lev) > len(lab):
+ taken = lev._box_values(com.take_1d(lev.values, lab))
+ elif box:
+ taken = com.take_1d(lev._box_values(lev.values), lab,
+ fill_value=_get_na_value(lev.dtype.type))
+ else:
+ taken = com.take_1d(lev.values, lab)
values.append(taken)
self._tuples = lib.fast_zip(values)
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index a8c4548f462ac..3c5f3a8d6b6d3 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -2335,6 +2335,18 @@ def test_from_product_datetimeindex(self):
(2, pd.Timestamp('2000-01-02'))])
assert_array_equal(mi.values, etalon)
+ def test_values_boxed(self):
+ tuples = [(1, pd.Timestamp('2000-01-01')),
+ (2, pd.NaT),
+ (3, pd.Timestamp('2000-01-03')),
+ (1, pd.Timestamp('2000-01-04')),
+ (2, pd.Timestamp('2000-01-02')),
+ (3, pd.Timestamp('2000-01-03'))]
+ mi = pd.MultiIndex.from_tuples(tuples)
+ assert_array_equal(mi.values, pd.lib.list_to_object_array(tuples))
+ # Check that code branches for boxed values produce identical results
+ assert_array_equal(mi.values[:4], mi[:4].values)
+
def test_append(self):
result = self.index[:3].append(self.index[3:])
self.assertTrue(result.equals(self.index))
diff --git a/vb_suite/index_object.py b/vb_suite/index_object.py
index de60a44e23a52..d54845f4643cd 100644
--- a/vb_suite/index_object.py
+++ b/vb_suite/index_object.py
@@ -108,7 +108,7 @@
# Constructing MultiIndex from cartesian product of iterables
-#
+#
setup = common_setup + """
iterables = [tm.makeStringIndex(10000), xrange(20)]
@@ -123,10 +123,17 @@
setup = common_setup + """
level1 = range(1000)
-level2 = date_range(start='1/1/2012', periods=10)
+level2 = date_range(start='1/1/2012', periods=100)
+mi = MultiIndex.from_product([level1, level2])
"""
-multiindex_with_datetime_level = \
- Benchmark("MultiIndex.from_product([level1, level2]).values", setup,
- name='multiindex_with_datetime_level',
+multiindex_with_datetime_level_full = \
+ Benchmark("mi.copy().values", setup,
+ name='multiindex_with_datetime_level_full',
+ start_date=datetime(2014, 10, 11))
+
+
+multiindex_with_datetime_level_sliced = \
+ Benchmark("mi[:10].values", setup,
+ name='multiindex_with_datetime_level_sliced',
start_date=datetime(2014, 10, 11))
| Corrects some deficiencies noted here: https://github.com/pydata/pandas/pull/8544#issuecomment-58909397. Adds a test case and an additional vbench test.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8549 | 2014-10-13T16:14:02Z | 2014-10-15T18:21:23Z | 2014-10-15T18:21:23Z | 2014-10-15T18:21:27Z |
BUG: inconsistent and undocumented option "converters" to read_excel | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 1d83e06a13567..00e86d971182d 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -1992,6 +1992,27 @@ indices to be parsed.
read_excel('path_to_file.xls', 'Sheet1', parse_cols=[0, 2, 3])
+.. note::
+
+ It is possible to transform the contents of Excel cells via the `converters`
+ option. For instance, to convert a column to boolean:
+
+ .. code-block:: python
+
+ read_excel('path_to_file.xls', 'Sheet1', converters={'MyBools': bool})
+
+ This options handles missing values and treats exceptions in the converters
+ as missing data. Transformations are applied cell by cell rather than to the
+ column as a whole, so the array dtype is not guaranteed. For instance, a
+ column of integers with missing values cannot be transformed to an array
+ with integer dtype, because NaN is strictly a float. You can manually mask
+ missing data to recover integer dtype:
+
+ .. code-block:: python
+
+ cfun = lambda x: int(x) if x else -1
+ read_excel('path_to_file.xls', 'Sheet1', converters={'MyInts': cfun})
+
To write a DataFrame object to a sheet of an Excel file, you can use the
``to_excel`` instance method. The arguments are largely the same as ``to_csv``
described above, the first argument being the name of the excel file, and the
diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index 424518cbde4f8..2ece91b5dea11 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -83,6 +83,11 @@ def read_excel(io, sheetname=0, **kwds):
Rows to skip at the beginning (0-indexed)
skip_footer : int, default 0
Rows at the end to skip (0-indexed)
+ converters : dict, default None
+ Dict of functions for converting values in certain columns. Keys can
+ either be integers or column labels, values are functions that take one
+ input argument, the Excel cell content, and return the transformed
+ content.
index_col : int, default None
Column to use as the row labels of the DataFrame. Pass None if
there is no such column
@@ -175,7 +180,7 @@ def __init__(self, io, **kwds):
def parse(self, sheetname=0, header=0, skiprows=None, skip_footer=0,
index_col=None, parse_cols=None, parse_dates=False,
date_parser=None, na_values=None, thousands=None, chunksize=None,
- convert_float=True, has_index_names=False, **kwds):
+ convert_float=True, has_index_names=False, converters=None, **kwds):
"""Read an Excel table into DataFrame
Parameters
@@ -188,6 +193,9 @@ def parse(self, sheetname=0, header=0, skiprows=None, skip_footer=0,
Rows to skip at the beginning (0-indexed)
skip_footer : int, default 0
Rows at the end to skip (0-indexed)
+ converters : dict, default None
+ Dict of functions for converting values in certain columns. Keys can
+ either be integers or column labels
index_col : int, default None
Column to use as the row labels of the DataFrame. Pass None if
there is no such column
@@ -235,6 +243,7 @@ def parse(self, sheetname=0, header=0, skiprows=None, skip_footer=0,
thousands=thousands, chunksize=chunksize,
skip_footer=skip_footer,
convert_float=convert_float,
+ converters=converters,
**kwds)
def _should_parse(self, i, parse_cols):
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 8f8e3151d56e6..b23aa017138e1 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -127,7 +127,7 @@ class ParserWarning(Warning):
Return TextFileReader object for iteration
skipfooter : int, default 0
Number of lines at bottom of file to skip (Unsupported with engine='c')
-converters : dict. optional
+converters : dict, default None
Dict of functions for converting values in certain columns. Keys can either
be integers or column labels
verbose : boolean, default False
@@ -983,8 +983,13 @@ def _convert_to_ndarrays(self, dct, na_values, na_fvalues, verbose=False,
na_fvalues)
coerce_type = True
if conv_f is not None:
- values = lib.map_infer(values, conv_f)
+ try:
+ values = lib.map_infer(values, conv_f)
+ except ValueError:
+ mask = lib.ismember(values, na_values).view(np.uin8)
+ values = lib.map_infer_mask(values, conv_f, mask)
coerce_type = False
+
cvals, na_count = self._convert_types(
values, set(col_na_values) | col_na_fvalues, coerce_type)
result[c] = cvals
@@ -1269,6 +1274,11 @@ def TextParser(*args, **kwds):
Row numbers to skip
skip_footer : int
Number of line at bottom of file to skip
+ converters : dict, default None
+ Dict of functions for converting values in certain columns. Keys can
+ either be integers or column labels, values are functions that take one
+ input argument, the cell (not column) content, and return the
+ transformed content.
encoding : string, default None
Encoding to use for UTF when reading/writing (ex. 'utf-8')
squeeze : boolean, default False
diff --git a/pandas/io/tests/data/test_converters.xls b/pandas/io/tests/data/test_converters.xls
new file mode 100644
index 0000000000000..c0aa9d903adad
Binary files /dev/null and b/pandas/io/tests/data/test_converters.xls differ
diff --git a/pandas/io/tests/data/test_converters.xlsx b/pandas/io/tests/data/test_converters.xlsx
new file mode 100644
index 0000000000000..e21bc5fbf9ee2
Binary files /dev/null and b/pandas/io/tests/data/test_converters.xlsx differ
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 6d3f0b5475298..4f97cef3d46d3 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -399,6 +399,31 @@ def test_reader_special_dtypes(self):
convert_float=False)
tm.assert_frame_equal(actual, no_convert_float)
+ # GH8212 - support for converters and missing values
+ def test_reader_converters(self):
+ _skip_if_no_xlrd()
+
+ expected = DataFrame.from_items([
+ ("IntCol", [1, 2, -3, -1000, 0]),
+ ("FloatCol", [12.5, np.nan, 18.3, 19.2, 0.000000005]),
+ ("BoolCol", ['Found', 'Found', 'Found', 'Not found', 'Found']),
+ ("StrCol", ['1', np.nan, '3', '4', '5']),
+ ])
+
+ converters = {'IntCol': lambda x: int(x) if x != '' else -1000,
+ 'FloatCol': lambda x: 10 * x if x else np.nan,
+ 2: lambda x: 'Found' if x != '' else 'Not found',
+ 3: lambda x: str(x) if x else '',
+ }
+
+ xlsx_path = os.path.join(self.dirpath, 'test_converters.xlsx')
+ xls_path = os.path.join(self.dirpath, 'test_converters.xls')
+
+ # should read in correctly and set types of single cells (not array dtypes)
+ for path in (xls_path, xlsx_path):
+ actual = read_excel(path, 'Sheet1', converters=converters)
+ tm.assert_frame_equal(actual, expected)
+
def test_reader_seconds(self):
# Test reading times with and without milliseconds. GH5945.
_skip_if_no_xlrd()
| Issue #8212 (first part): pandas.read_excel accepts an optional argument "converters" (which is passed down to PythonParser) to convert single cells in columns with a conversion function. I documented this feature and added a try/except block to make it work in case some cells contain NaNs.
What's still missing is the full "dtype" argument, a la read_csv. That patch is somewhat orthogonal because it only works with the C parser, so I plan to implement it in a second step.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8548 | 2014-10-13T12:31:11Z | 2014-11-15T19:01:57Z | 2014-11-15T19:01:57Z | 2014-11-15T20:38:38Z |
PERF: upgrade khash lib to 0.2.8 | diff --git a/pandas/hashtable.pyx b/pandas/hashtable.pyx
index cf9428d5862ec..37abcf6d6ec73 100644
--- a/pandas/hashtable.pyx
+++ b/pandas/hashtable.pyx
@@ -1,4 +1,5 @@
-from cpython cimport PyObject, Py_INCREF, PyList_Check, PyTuple_Check
+from cpython cimport (PyObject, Py_INCREF, PyList_Check, PyTuple_Check,
+ PyString_AsStringAndSize, PyDict_Copy)
from khash cimport *
from numpy cimport *
@@ -843,6 +844,127 @@ cdef class PyObjectHashTable(HashTable):
return labels
+cdef inline cbuf_t to_cbuf(object s):
+ cdef cbuf_t output
+ PyString_AsStringAndSize(s, <char**>&output.buf, &output.len)
+ return output
+
+
+cdef class CBufHashTable(HashTable):
+ cdef kh_cbuf_map_t *table
+
+ def __cinit__(self, int size_hint=1):
+ self.table = kh_init_cbuf_map()
+ if size_hint is not None:
+ kh_resize_cbuf_map(self.table, size_hint)
+
+ def __dealloc__(self):
+ kh_destroy_cbuf_map(self.table)
+
+ cdef inline int check_type(self, object val):
+ return util.is_string_object(val)
+
+ cpdef get_item(self, object val):
+ cdef khiter_t it
+ it = kh_get_cbuf_map(self.table, to_cbuf(val))
+ if it != self.table.n_buckets:
+ return self.table.vals[it]
+ else:
+ raise KeyError(val)
+
+ def get_iter_test(self, object key, Py_ssize_t iterations):
+ cdef khiter_t it
+ cdef Py_ssize_t i, val
+ for i in range(iterations):
+ it = kh_get_cbuf_map(self.table, to_cbuf(key))
+ if it != self.table.n_buckets:
+ val = self.table.vals[it]
+
+ cpdef set_item(self, object key, Py_ssize_t val):
+ cdef:
+ khiter_t it
+ int ret = 0
+ cbuf_t buf
+
+ buf = to_cbuf(key)
+
+ it = kh_put_cbuf_map(self.table, buf, &ret)
+ self.table.keys[it] = buf
+ if kh_exist_cbuf_map(self.table, it):
+ self.table.vals[it] = val
+ else:
+ raise KeyError(key)
+
+ def get_indexer(self, ndarray[object] values):
+ cdef:
+ Py_ssize_t i, n = len(values)
+ ndarray[int64_t] labels = np.empty(n, dtype=np.int64)
+ cbuf_t buf
+ int64_t[::1] out = labels
+ khiter_t it
+ kh_cbuf_map_t *table = self.table
+
+ for i in range(n):
+ buf = to_cbuf(values[i])
+ it = kh_get_cbuf_map(table, buf)
+ if it != table.n_buckets:
+ out[i] = table.vals[it]
+ else:
+ out[i] = -1
+ return labels
+
+ def unique(self, ndarray[object] values):
+ cdef:
+ Py_ssize_t i, n = len(values)
+ Py_ssize_t idx, count = 0
+ int ret = 0
+ object val
+ cbuf_t buf
+ khiter_t it
+ ObjectVector uniques = ObjectVector()
+
+ for i in range(n):
+ val = values[i]
+ buf = to_cbuf(val)
+ it = kh_get_cbuf_map(self.table, buf)
+ if it == self.table.n_buckets:
+ it = kh_put_cbuf_map(self.table, buf, &ret)
+ count += 1
+ uniques.append(val)
+
+ return uniques.to_array()
+
+ def factorize(self, ndarray[object] values):
+ cdef:
+ Py_ssize_t i, n = len(values)
+ ndarray[int64_t] labels = np.empty(n, dtype=np.int64)
+ list reverse = []
+ Py_ssize_t idx, count = 0
+ int ret = 0
+ object val
+ cbuf_t buf
+ khiter_t it
+
+ for i in range(n):
+ val = values[i]
+ buf = to_cbuf(val)
+ it = kh_get_cbuf_map(self.table, buf)
+ if it != self.table.n_buckets:
+ idx = self.table.vals[it]
+ labels[i] = idx
+ else:
+ it = kh_put_cbuf_map(self.table, buf, &ret)
+
+ self.table.vals[it] = count
+ reverse.append(val)
+ labels[i] = count
+ count += 1
+
+ return PyDict_Copy(enumerate(reverse)), labels
+
+
+
+
cdef class Factorizer:
cdef public PyObjectHashTable table
cdef public ObjectVector uniques
diff --git a/pandas/src/khash.pxd b/pandas/src/khash.pxd
index a8fd51a62cfbe..622c0d70daaf0 100644
--- a/pandas/src/khash.pxd
+++ b/pandas/src/khash.pxd
@@ -17,7 +17,6 @@ cdef extern from "khash_python.h":
inline khint_t kh_get_pymap(kh_pymap_t*, PyObject*)
inline void kh_resize_pymap(kh_pymap_t*, khint_t)
inline khint_t kh_put_pymap(kh_pymap_t*, PyObject*, int*)
- inline void kh_del_pymap(kh_pymap_t*, khint_t)
bint kh_exist_pymap(kh_pymap_t*, khiter_t)
@@ -33,7 +32,6 @@ cdef extern from "khash_python.h":
inline khint_t kh_get_pyset(kh_pyset_t*, PyObject*)
inline void kh_resize_pyset(kh_pyset_t*, khint_t)
inline khint_t kh_put_pyset(kh_pyset_t*, PyObject*, int*)
- inline void kh_del_pyset(kh_pyset_t*, khint_t)
bint kh_exist_pyset(kh_pyset_t*, khiter_t)
@@ -51,7 +49,6 @@ cdef extern from "khash_python.h":
inline khint_t kh_get_str(kh_str_t*, kh_cstr_t)
inline void kh_resize_str(kh_str_t*, khint_t)
inline khint_t kh_put_str(kh_str_t*, kh_cstr_t, int*)
- inline void kh_del_str(kh_str_t*, khint_t)
bint kh_exist_str(kh_str_t*, khiter_t)
@@ -68,7 +65,6 @@ cdef extern from "khash_python.h":
inline khint_t kh_get_int64(kh_int64_t*, int64_t)
inline void kh_resize_int64(kh_int64_t*, khint_t)
inline khint_t kh_put_int64(kh_int64_t*, int64_t, int*)
- inline void kh_del_int64(kh_int64_t*, khint_t)
bint kh_exist_int64(kh_int64_t*, khiter_t)
@@ -84,7 +80,6 @@ cdef extern from "khash_python.h":
inline khint_t kh_get_float64(kh_float64_t*, float64_t)
inline void kh_resize_float64(kh_float64_t*, khint_t)
inline khint_t kh_put_float64(kh_float64_t*, float64_t, int*)
- inline void kh_del_float64(kh_float64_t*, khint_t)
bint kh_exist_float64(kh_float64_t*, khiter_t)
@@ -100,7 +95,6 @@ cdef extern from "khash_python.h":
inline khint_t kh_get_int32(kh_int32_t*, int32_t)
inline void kh_resize_int32(kh_int32_t*, khint_t)
inline khint_t kh_put_int32(kh_int32_t*, int32_t, int*)
- inline void kh_del_int32(kh_int32_t*, khint_t)
bint kh_exist_int32(kh_int32_t*, khiter_t)
@@ -118,7 +112,24 @@ cdef extern from "khash_python.h":
inline khint_t kh_get_strbox(kh_strbox_t*, kh_cstr_t)
inline void kh_resize_strbox(kh_strbox_t*, khint_t)
inline khint_t kh_put_strbox(kh_strbox_t*, kh_cstr_t, int*)
- inline void kh_del_strbox(kh_strbox_t*, khint_t)
bint kh_exist_strbox(kh_strbox_t*, khiter_t)
+ ctypedef struct cbuf_t:
+ kh_cstr_t buf
+ Py_ssize_t len
+
+ ctypedef struct kh_cbuf_map_t:
+ khint_t n_buckets, size, n_occupied, upper_bound
+ uint32_t *flags
+ cbuf_t *keys
+ size_t *vals
+
+ inline kh_cbuf_map_t* kh_init_cbuf_map()
+ inline void kh_destroy_cbuf_map(kh_cbuf_map_t*)
+ inline void kh_clear_cbuf_map(kh_cbuf_map_t*)
+ inline khint_t kh_get_cbuf_map(kh_cbuf_map_t*, cbuf_t)
+ inline void kh_resize_cbuf_map(kh_cbuf_map_t*, khint_t)
+ inline khint_t kh_put_cbuf_map(kh_cbuf_map_t*, cbuf_t, int*)
+
+ bint kh_exist_cbuf_map(kh_cbuf_map_t*, khiter_t)
diff --git a/pandas/src/klib/khash.h b/pandas/src/klib/khash.h
index 4350ff06f37f0..22eb46063cf60 100644
--- a/pandas/src/klib/khash.h
+++ b/pandas/src/klib/khash.h
@@ -47,6 +47,23 @@ int main() {
*/
/*
+ 2013-05-02 (0.2.8):
+
+ * Use quadratic probing. When the capacity is power of 2, stepping function
+ i*(i+1)/2 guarantees to traverse each bucket. It is better than double
+ hashing on cache performance and is more robust than linear probing.
+
+ In theory, double hashing should be more robust than quadratic probing.
+ However, my implementation is probably not for large hash tables, because
+ the second hash function is closely tied to the first hash function,
+ which reduce the effectiveness of double hashing.
+
+ Reference: http://research.cs.vt.edu/AVresearch/hashing/quadratic.php
+
+ 2011-12-29 (0.2.7):
+
+ * Minor code clean up; no actual effect.
+
2011-09-16 (0.2.6):
* The capacity is a power of 2. This seems to dramatically improve the
@@ -107,12 +124,13 @@ int main() {
Generic hash table library.
*/
-#define AC_VERSION_KHASH_H "0.2.6"
+#define AC_VERSION_KHASH_H "0.2.8"
#include <stdlib.h>
#include <string.h>
#include <limits.h>
+/* compiler specific configuration */
#if UINT_MAX == 0xffffffffu
typedef unsigned int khint32_t;
@@ -121,26 +139,20 @@ typedef unsigned long khint32_t;
#endif
#if ULONG_MAX == ULLONG_MAX
-typedef unsigned long khuint64_t;
-typedef signed long khint64_t;
+typedef unsigned long khint64_t;
#else
-typedef unsigned long long khuint64_t;
-typedef signed long long khint64_t;
+typedef unsigned long long khint64_t;
#endif
typedef double khfloat64_t;
-#ifndef PANDAS_INLINE
- #if defined(__GNUC__)
- #define PANDAS_INLINE __inline__
- #elif defined(_MSC_VER)
- #define PANDAS_INLINE __inline
- #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
- #define PANDAS_INLINE inline
- #else
- #define PANDAS_INLINE
- #endif
+#ifndef kh_inline
+#ifdef _MSC_VER
+#define kh_inline __inline
+#else
+#define kh_inline inline
#endif
+#endif /* kh_inline */
typedef khint32_t khint_t;
typedef khint_t khiter_t;
@@ -154,11 +166,6 @@ typedef khint_t khiter_t;
#define __ac_set_isboth_false(flag, i) __ac_set_isempty_false(flag, i)
#define __ac_set_isdel_true(flag, i) (0)
-#ifdef KHASH_LINEAR
-#define __ac_inc(k, m) 1
-#else
-#define __ac_inc(k, m) (((k)>>3 ^ (k)<<3) | 1) & (m)
-#endif
#define __ac_fsize(m) ((m) < 32? 1 : (m)>>5)
@@ -166,39 +173,47 @@ typedef khint_t khiter_t;
#define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x))
#endif
+#ifndef kcalloc
+#define kcalloc(N,Z) calloc(N,Z)
+#endif
+#ifndef kmalloc
+#define kmalloc(Z) malloc(Z)
+#endif
+#ifndef krealloc
+#define krealloc(P,Z) realloc(P,Z)
+#endif
+#ifndef kfree
+#define kfree(P) free(P)
+#endif
+
static const double __ac_HASH_UPPER = 0.77;
-#define KHASH_DECLARE(name, khkey_t, khval_t) \
- typedef struct { \
- khint_t n_buckets, size, n_occupied, upper_bound; \
- khint32_t *flags; \
- khkey_t *keys; \
- khval_t *vals; \
- } kh_##name##_t; \
- extern kh_##name##_t *kh_init_##name(); \
+#define __KHASH_TYPE(name, khkey_t, khval_t) \
+ typedef struct { \
+ khint_t n_buckets, size, n_occupied, upper_bound; \
+ khint32_t *flags; \
+ khkey_t *keys; \
+ khval_t *vals; \
+ } kh_##name##_t;
+
+#define __KHASH_PROTOTYPES(name, khkey_t, khval_t) \
+ extern kh_##name##_t *kh_init_##name(void); \
extern void kh_destroy_##name(kh_##name##_t *h); \
extern void kh_clear_##name(kh_##name##_t *h); \
extern khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key); \
- extern void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets); \
- extern khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret); \
- extern void kh_del_##name(kh_##name##_t *h, khint_t x);
+ extern int kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets); \
+ extern khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret);
-#define KHASH_INIT2(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \
- typedef struct { \
- khint_t n_buckets, size, n_occupied, upper_bound; \
- khint32_t *flags; \
- khkey_t *keys; \
- khval_t *vals; \
- } kh_##name##_t; \
+#define __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \
SCOPE kh_##name##_t *kh_init_##name(void) { \
- return (kh_##name##_t*)calloc(1, sizeof(kh_##name##_t)); \
+ return (kh_##name##_t*)kcalloc(1, sizeof(kh_##name##_t)); \
} \
SCOPE void kh_destroy_##name(kh_##name##_t *h) \
{ \
if (h) { \
- free(h->keys); free(h->flags); \
- free(h->vals); \
- free(h); \
+ kfree((void *)h->keys); kfree(h->flags); \
+ kfree((void *)h->vals); \
+ kfree(h); \
} \
} \
SCOPE void kh_clear_##name(kh_##name##_t *h) \
@@ -211,19 +226,19 @@ static const double __ac_HASH_UPPER = 0.77;
SCOPE khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key) \
{ \
if (h->n_buckets) { \
- khint_t inc, k, i, last, mask; \
+ khint_t k, i, last, mask, step = 0; \
mask = h->n_buckets - 1; \
k = __hash_func(key); i = k & mask; \
- inc = __ac_inc(k, mask); last = i; /* inc==1 for linear probing */ \
+ last = i; \
while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || !__hash_equal(h->keys[i], key))) { \
- i = (i + inc) & mask; \
+ i = (i + (++step)) & mask; \
if (i == last) return h->n_buckets; \
} \
return __ac_iseither(h->flags, i)? h->n_buckets : i; \
} else return 0; \
} \
- SCOPE void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets) \
- { /* This function uses 0.25*n_bucktes bytes of working space instead of [sizeof(key_t+val_t)+.25]*n_buckets. */ \
+ SCOPE int kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets) \
+ { /* This function uses 0.25*n_buckets bytes of working space instead of [sizeof(key_t+val_t)+.25]*n_buckets. */ \
khint32_t *new_flags = 0; \
khint_t j = 1; \
{ \
@@ -231,11 +246,18 @@ static const double __ac_HASH_UPPER = 0.77;
if (new_n_buckets < 4) new_n_buckets = 4; \
if (h->size >= (khint_t)(new_n_buckets * __ac_HASH_UPPER + 0.5)) j = 0; /* requested size is too small */ \
else { /* hash table size to be changed (shrink or expand); rehash */ \
- new_flags = (khint32_t*)malloc(__ac_fsize(new_n_buckets) * sizeof(khint32_t)); \
+ new_flags = (khint32_t*)kmalloc(__ac_fsize(new_n_buckets) * sizeof(khint32_t)); \
+ if (!new_flags) return -1; \
memset(new_flags, 0xff, __ac_fsize(new_n_buckets) * sizeof(khint32_t)); \
if (h->n_buckets < new_n_buckets) { /* expand */ \
- h->keys = (khkey_t*)realloc(h->keys, new_n_buckets * sizeof(khkey_t)); \
- if (kh_is_map) h->vals = (khval_t*)realloc(h->vals, new_n_buckets * sizeof(khval_t)); \
+ khkey_t *new_keys = (khkey_t*)krealloc((void *)h->keys, new_n_buckets * sizeof(khkey_t)); \
+ if (!new_keys) { kfree(new_flags); return -1; } \
+ h->keys = new_keys; \
+ if (kh_is_map) { \
+ khval_t *new_vals = (khval_t*)krealloc((void *)h->vals, new_n_buckets * sizeof(khval_t)); \
+ if (!new_vals) { kfree(new_flags); return -1; } \
+ h->vals = new_vals; \
+ } \
} /* otherwise shrink */ \
} \
} \
@@ -249,11 +271,10 @@ static const double __ac_HASH_UPPER = 0.77;
if (kh_is_map) val = h->vals[j]; \
__ac_set_isempty_true(h->flags, j); \
while (1) { /* kick-out process; sort of like in Cuckoo hashing */ \
- khint_t inc, k, i; \
+ khint_t k, i, step = 0; \
k = __hash_func(key); \
i = k & new_mask; \
- inc = __ac_inc(k, new_mask); \
- while (!__ac_isempty(new_flags, i)) i = (i + inc) & new_mask; \
+ while (!__ac_isempty(new_flags, i)) i = (i + (++step)) & new_mask; \
__ac_set_isempty_false(new_flags, i); \
if (i < h->n_buckets && __ac_iseither(h->flags, i) == 0) { /* kick out the existing element */ \
{ khkey_t tmp = h->keys[i]; h->keys[i] = key; key = tmp; } \
@@ -268,32 +289,38 @@ static const double __ac_HASH_UPPER = 0.77;
} \
} \
if (h->n_buckets > new_n_buckets) { /* shrink the hash table */ \
- h->keys = (khkey_t*)realloc(h->keys, new_n_buckets * sizeof(khkey_t)); \
- if (kh_is_map) h->vals = (khval_t*)realloc(h->vals, new_n_buckets * sizeof(khval_t)); \
+ h->keys = (khkey_t*)krealloc((void *)h->keys, new_n_buckets * sizeof(khkey_t)); \
+ if (kh_is_map) h->vals = (khval_t*)krealloc((void *)h->vals, new_n_buckets * sizeof(khval_t)); \
} \
- free(h->flags); /* free the working space */ \
+ kfree(h->flags); /* free the working space */ \
h->flags = new_flags; \
h->n_buckets = new_n_buckets; \
h->n_occupied = h->size; \
h->upper_bound = (khint_t)(h->n_buckets * __ac_HASH_UPPER + 0.5); \
} \
+ return 0; \
} \
SCOPE khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret) \
{ \
khint_t x; \
if (h->n_occupied >= h->upper_bound) { /* update the hash table */ \
- if (h->n_buckets > (h->size<<1)) kh_resize_##name(h, h->n_buckets - 1); /* clear "deleted" elements */ \
- else kh_resize_##name(h, h->n_buckets + 1); /* expand the hash table */ \
+ if (h->n_buckets > (h->size<<1)) { \
+ if (kh_resize_##name(h, h->n_buckets - 1) < 0) { /* clear "deleted" elements */ \
+ *ret = -1; return h->n_buckets; \
+ } \
+ } else if (kh_resize_##name(h, h->n_buckets + 1) < 0) { /* expand the hash table */ \
+ *ret = -1; return h->n_buckets; \
+ } \
} /* TODO: to implement automatically shrinking; resize() already support shrinking */ \
{ \
- khint_t inc, k, i, site, last, mask = h->n_buckets - 1; \
+ khint_t k, i, site, last, mask = h->n_buckets - 1, step = 0; \
x = site = h->n_buckets; k = __hash_func(key); i = k & mask; \
if (__ac_isempty(h->flags, i)) x = i; /* for speed up */ \
else { \
- inc = __ac_inc(k, mask); last = i; \
+ last = i; \
while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || !__hash_equal(h->keys[i], key))) { \
if (__ac_isdel(h->flags, i)) site = i; \
- i = (i + inc) & mask; \
+ i = (i + (++step)) & mask; \
if (i == last) { x = site; break; } \
} \
if (x == h->n_buckets) { \
@@ -314,17 +341,18 @@ static const double __ac_HASH_UPPER = 0.77;
*ret = 2; \
} else *ret = 0; /* Don't touch h->keys[x] if present and not deleted */ \
return x; \
- } \
- SCOPE void kh_del_##name(kh_##name##_t *h, khint_t x) \
- { \
- if (x != h->n_buckets && !__ac_iseither(h->flags, x)) { \
- __ac_set_isdel_true(h->flags, x); \
- --h->size; \
- } \
}
+#define KHASH_DECLARE(name, khkey_t, khval_t) \
+ __KHASH_TYPE(name, khkey_t, khval_t) \
+ __KHASH_PROTOTYPES(name, khkey_t, khval_t)
+
+#define KHASH_INIT2(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \
+ __KHASH_TYPE(name, khkey_t, khval_t) \
+ __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal)
+
#define KHASH_INIT(name, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \
- KHASH_INIT2(name, static PANDAS_INLINE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal)
+ KHASH_INIT2(name, static kh_inline, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal)
/* --- BEGIN OF HASH FUNCTIONS --- */
@@ -354,10 +382,10 @@ static const double __ac_HASH_UPPER = 0.77;
@param s Pointer to a null terminated string
@return The hash value
*/
-static PANDAS_INLINE khint_t __ac_X31_hash_string(const char *s)
+static kh_inline khint_t __ac_X31_hash_string(const char *s)
{
- khint_t h = *s;
- if (h) for (++s ; *s; ++s) h = (h << 5) - h + *s;
+ khint_t h = (khint_t)*s;
+ if (h) for (++s ; *s; ++s) h = (h << 5) - h + (khint_t)*s;
return h;
}
/*! @function
@@ -371,7 +399,7 @@ static PANDAS_INLINE khint_t __ac_X31_hash_string(const char *s)
*/
#define kh_str_hash_equal(a, b) (strcmp(a, b) == 0)
-static PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key)
+static kh_inline khint_t __ac_Wang_hash(khint_t key)
{
key += ~(key << 15);
key ^= (key >> 10);
@@ -427,7 +455,8 @@ static PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key)
@param name Name of the hash table [symbol]
@param h Pointer to the hash table [khash_t(name)*]
@param k Key [type of keys]
- @param r Extra return code: 0 if the key is present in the hash table;
+ @param r Extra return code: -1 if the operation failed;
+ 0 if the key is present in the hash table;
1 if the bucket is empty (never used); 2 if the element in
the bucket has been deleted [int*]
@return Iterator to the inserted element [khint_t]
@@ -439,18 +468,10 @@ static PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key)
@param name Name of the hash table [symbol]
@param h Pointer to the hash table [khash_t(name)*]
@param k Key [type of keys]
- @return Iterator to the found element, or kh_end(h) is the element is absent [khint_t]
+ @return Iterator to the found element, or kh_end(h) if the element is absent [khint_t]
*/
#define kh_get(name, h, k) kh_get_##name(h, k)
-/*! @function
- @abstract Remove a key from the hash table.
- @param name Name of the hash table [symbol]
- @param h Pointer to the hash table [khash_t(name)*]
- @param k Iterator to the element to be deleted [khint_t]
- */
-#define kh_del(name, h, k) kh_del_##name(h, k)
-
/*! @function
@abstract Test whether a bucket contains data.
@param h Pointer to the hash table [khash_t(name)*]
@@ -509,6 +530,34 @@ static PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key)
*/
#define kh_n_buckets(h) ((h)->n_buckets)
+/*! @function
+ @abstract Iterate over the entries in the hash table
+ @param h Pointer to the hash table [khash_t(name)*]
+ @param kvar Variable to which key will be assigned
+ @param vvar Variable to which value will be assigned
+ @param code Block of code to execute
+ */
+#define kh_foreach(h, kvar, vvar, code) { khint_t __i; \
+ for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \
+ if (!kh_exist(h,__i)) continue; \
+ (kvar) = kh_key(h,__i); \
+ (vvar) = kh_val(h,__i); \
+ code; \
+ } }
+
+/*! @function
+ @abstract Iterate over the values in the hash table
+ @param h Pointer to the hash table [khash_t(name)*]
+ @param vvar Variable to which value will be assigned
+ @param code Block of code to execute
+ */
+#define kh_foreach_value(h, vvar, code) { khint_t __i; \
+ for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \
+ if (!kh_exist(h,__i)) continue; \
+ (vvar) = kh_val(h,__i); \
+ code; \
+ } }
+
/* More conenient interfaces */
/*! @function
@@ -530,9 +579,6 @@ static PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key)
@abstract Instantiate a hash map containing 64-bit integer keys
@param name Name of the hash table [symbol]
*/
-#define KHASH_SET_INIT_UINT64(name) \
- KHASH_INIT(name, khuint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal)
-
#define KHASH_SET_INIT_INT64(name) \
KHASH_INIT(name, khint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal)
@@ -541,13 +587,9 @@ static PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key)
@param name Name of the hash table [symbol]
@param khval_t Type of values [type]
*/
-#define KHASH_MAP_INIT_UINT64(name, khval_t) \
- KHASH_INIT(name, khuint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal)
-
#define KHASH_MAP_INIT_INT64(name, khval_t) \
KHASH_INIT(name, khint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal)
-
typedef const char *kh_cstr_t;
/*! @function
@abstract Instantiate a hash map containing const char* keys
@@ -565,14 +607,4 @@ typedef const char *kh_cstr_t;
KHASH_INIT(name, kh_cstr_t, khval_t, 1, kh_str_hash_func, kh_str_hash_equal)
-#define kh_exist_str(h, k) (kh_exist(h, k))
-#define kh_exist_float64(h, k) (kh_exist(h, k))
-#define kh_exist_int64(h, k) (kh_exist(h, k))
-#define kh_exist_int32(h, k) (kh_exist(h, k))
-
-KHASH_MAP_INIT_STR(str, size_t)
-KHASH_MAP_INIT_INT(int32, size_t)
-KHASH_MAP_INIT_INT64(int64, size_t)
-
-
#endif /* __AC_KHASH_H */
diff --git a/pandas/src/klib/khash_python.h b/pandas/src/klib/khash_python.h
index d3ef48de0f831..e196e9b23434f 100644
--- a/pandas/src/klib/khash_python.h
+++ b/pandas/src/klib/khash_python.h
@@ -1,7 +1,126 @@
+#ifndef _KLIB_KHASH_PYTHON_H_
+#define _KLIB_KHASH_PYTHON_H_
+
#include <Python.h>
+#ifndef PANDAS_INLINE
+ #if defined(__GNUC__)
+ #define PANDAS_INLINE __inline__
+ #elif defined(_MSC_VER)
+ #define PANDAS_INLINE __inline
+ #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+ #define PANDAS_INLINE inline
+ #else
+ #define PANDAS_INLINE
+ #endif
+#endif
+
+#define kh_inline PANDAS_INLINE
#include "khash.h"
+#define kh_exist_str(h, k) (kh_exist(h, k))
+#define kh_exist_float64(h, k) (kh_exist(h, k))
+#define kh_exist_int64(h, k) (kh_exist(h, k))
+#define kh_exist_int32(h, k) (kh_exist(h, k))
+
+#include "xxhash/xxhash.h"
+
+/*
+ * By default khash uses crappy x31 hash function which puts strings that
+ * differ only in the last character into neighbouring buckets which is not
+ * good given that quadratic probing tries small steps first.
+ *
+ * xxhash gives better bucket distribution and performance-wise is great for
+ * long-ish strings, but it is a bit slower than x31 on the shortest ones
+ * (turns out at length == 2 the difference is already negligible).
+ *
+ * Inlining will hinder merging in upstream releases, but 1-character strings
+ * are a valid use case for pandas, so let's pre-calculate a vector of 256
+ * values to avoid calling two functions (strlen and XXH32) if there's only one
+ * character to hash.
+ *
+ * This table was generated with the following code. Feel free to re-run it if
+ * an update comes in:
+
+#include <stdio.h>
+#include "xxhash.h"
+
+int main(int argc, char *argv[])
+{
+ printf("static khint_t XXH32_EMPTY_HASH = 0x%08x;\n",
+ XXH32("", 0, 0xdeadbeef));
+ printf("static khint_t XXH32_ONECHAR_HASH[256] = {");
+ unsigned char s[2] = {0};
+ for (int i = 0; i < 256; ++i) {
+ if (i % 8 == 0) {
+ printf("\n ");
+ }
+ s[0] = i;
+ printf("0x%08x", XXH32(s, 1, 0xdeadbeef));
+ if (i < 255) {
+ printf(", ");
+ }
+ }
+ printf("\n};\n");
+ return 0;
+}
+*/
+
+static khint_t XXH32_EMPTY_HASH = 0xc372c6cb;
+static khint_t XXH32_ONECHAR_HASH[256] = {
+ 0x39110451, 0xd3efa134, 0xea8d6dc4, 0xe59a066b, 0x89f3a4f5, 0xdcce5bc9, 0x44be0c3e, 0x96469248,
+ 0x7885ddeb, 0x24417b24, 0xb77b30b2, 0xa83d21eb, 0x6f6ba52b, 0x7315bbe5, 0xce858701, 0x52299f26,
+ 0x440ec810, 0xd02a934f, 0xf873d394, 0xd168a8e1, 0x31c30198, 0x37c3967b, 0xc1bdbdf8, 0x3ddaf3cc,
+ 0xb7222f4a, 0x96625cdf, 0xabf92a2f, 0x69e97975, 0x55f24523, 0x6b1abaa0, 0xe5b033ab, 0x9e21842c,
+ 0x3ac2a339, 0x827b0af2, 0xd7ea0f97, 0x72317ee6, 0xe6bd4439, 0xb0b183f1, 0xca90e5e0, 0x57960753,
+ 0x6eefe374, 0xb9c9c5b5, 0x57396d1f, 0x6db79351, 0xab55c12d, 0x32229df4, 0xbfa3a164, 0x58f9f4ba,
+ 0x5987c643, 0xffbfa961, 0x1080d4eb, 0xc5c3d846, 0x16a7fd8e, 0xed29fd3a, 0x8d78613d, 0xd088b720,
+ 0x8d597f4c, 0x2df1ce8f, 0x79bc5215, 0x749d67c1, 0xa9ad300c, 0x60c6237d, 0xeeb080e7, 0xb74eef62,
+ 0x6ddba2f2, 0x3d9f18cf, 0x0b6ad1bd, 0xc7a33d19, 0x3cb6352f, 0x872839f9, 0x259ced1e, 0x0f9d713b,
+ 0x6816620f, 0x8d2c96a7, 0x377fb2f9, 0x2616b5b5, 0x9bae3a05, 0x8368a004, 0x3a67fd94, 0x312529c4,
+ 0xc9238f87, 0x3e85e142, 0x973dedc6, 0xcbc3d4ba, 0xd2629b58, 0x2aae9a6d, 0x82ffc598, 0x4a8512b3,
+ 0x51146ceb, 0x85ddc3f4, 0xa83b942f, 0x55769a32, 0xf7fa3fdf, 0xfbe35842, 0x342ff574, 0x848400a6,
+ 0x92707153, 0x48cd58fd, 0xbdae4a11, 0x701bbadb, 0x4a5b37c4, 0x98770eeb, 0xfc1b98fc, 0x05dd6894,
+ 0xd3ba005c, 0x453bc774, 0xfe186d14, 0xa25acde2, 0xcc738313, 0x1dbdefa7, 0x83ed6f1e, 0xf9d8e195,
+ 0x5f10c546, 0xf22c5a0f, 0x31da5f5e, 0x5341c163, 0xabd3f750, 0x882e33d8, 0x4d8105cd, 0xc1f6f3d9,
+ 0x347e1d5c, 0xdb06193c, 0x64841a53, 0x3991a6e6, 0x0abdd625, 0xedcf00f7, 0xa8e64229, 0x2fc9029b,
+ 0x4fc5ca41, 0x1f5aaae5, 0x29bdda91, 0x55446dae, 0x1566ec40, 0x9ac8391e, 0xcd4d6ab1, 0x0f3807f6,
+ 0xf3be6887, 0x9f4b88bd, 0x33c401df, 0xaa9df64f, 0xce5c70ac, 0x9ee55a87, 0x4cb91c84, 0x8c322b3d,
+ 0x8e40fb24, 0x3af430fb, 0xeea567c2, 0xe80c7dc2, 0x6f619449, 0xe0ca8048, 0x984c626e, 0x50bf1281,
+ 0x4895cbee, 0x5d016a96, 0xe58b8980, 0x3457ef7c, 0x2a24f819, 0x0641cc30, 0xbddc5f84, 0x03ce4656,
+ 0xbcb73c9c, 0xcd29be82, 0x0930d945, 0xf3fc8e3c, 0xbed775cd, 0xd6668fae, 0x6876f949, 0xcf34fbd7,
+ 0x0537d916, 0x7efd5f26, 0xb2d32520, 0x10d58995, 0x19d64e1c, 0xacae767c, 0xf23a4e7d, 0xdcb654fe,
+ 0xe1ec9a9f, 0x3061302b, 0x453a0b7c, 0xe845436e, 0xb2b690df, 0x245c17b5, 0x756a9374, 0x470998f5,
+ 0xe31a5f5b, 0x60dbad02, 0xf738299d, 0x0db8b11a, 0xd34cb801, 0xb2f3597d, 0xa627e466, 0xda4f9935,
+ 0x5c58e1df, 0x4b5319d6, 0x48acc08f, 0xce18d68e, 0xeb995e7f, 0x11a07cba, 0x025127b2, 0xd1325331,
+ 0x55d76240, 0x281bba14, 0xb9ac069d, 0x25e60bcc, 0xf077fbd3, 0xe460ece9, 0x725a9971, 0xa6b5c6b4,
+ 0xe5f216a3, 0xbee80d71, 0x1a049114, 0x851012d4, 0xa6e175cc, 0x6ec98c95, 0x56a77202, 0x7e2ab05f,
+ 0x4850279c, 0x1b009afe, 0xf71e36b6, 0x9cadc37a, 0x43a167da, 0x5d75b5f3, 0xc432215c, 0x93ff1905,
+ 0x8764d057, 0xf44cd35d, 0x03d3a324, 0xd65a5047, 0xe872b4d8, 0x8dcb9a23, 0xfebf9113, 0x59701be9,
+ 0xdf9f6090, 0xce9b2907, 0x664c6a5a, 0x81bfefc4, 0x13829979, 0xda98b6ab, 0x7b7e9ff0, 0x13c24005,
+ 0xcee61b6b, 0x15737a85, 0xe2f95e48, 0xf2136570, 0xd1ccfdab, 0xa9adfb16, 0x1f7339a9, 0x83247f43,
+ 0x68c6c8bf, 0x5046f6fc, 0x2d3dea84, 0x79a0be74, 0x39dd7eb3, 0x4d5cc636, 0xe4e1352d, 0xd1317a99
+};
+
+/* Seed value is chosen arbitrarily. */
+static khint_t XXH32_SEED = 0xdeadbeef;
+
+static khint_t PANDAS_INLINE str_xxhash_hash_func(kh_cstr_t key) {
+ if (!key[0]) {
+ return XXH32_EMPTY_HASH;
+ }
+ if (!key[1]) {
+ return XXH32_ONECHAR_HASH[(uint8_t)key[0]];
+ }
+ return XXH32(key, strlen(key), XXH32_SEED);
+}
+
+KHASH_INIT(str, kh_cstr_t, size_t, 1,
+ str_xxhash_hash_func, kh_str_hash_equal)
+
+KHASH_MAP_INIT_INT(int32, size_t)
+KHASH_MAP_INIT_INT64(int64, size_t)
+
// kludge
#define kh_float64_hash_func _Py_HashDouble
@@ -13,7 +132,7 @@
KHASH_MAP_INIT_FLOAT64(float64, size_t)
-int PANDAS_INLINE pyobject_cmp(PyObject* a, PyObject* b) {
+static int PANDAS_INLINE pyobject_cmp(PyObject* a, PyObject* b) {
int result = PyObject_RichCompareBool(a, b, Py_EQ);
if (result < 0) {
PyErr_Clear();
@@ -46,4 +165,44 @@ KHASH_SET_INIT_PYOBJECT(pyset)
#define kh_exist_pymap(h, k) (kh_exist(h, k))
#define kh_exist_pyset(h, k) (kh_exist(h, k))
-KHASH_MAP_INIT_STR(strbox, kh_pyobject_t)
+KHASH_INIT(strbox, kh_cstr_t, kh_pyobject_t, 1,
+ str_xxhash_hash_func, kh_str_hash_equal)
+
+/* Plain old C buffer structure */
+typedef struct {
+ kh_cstr_t buf;
+ Py_ssize_t len;
+} cbuf_t;
+
+static khint_t PANDAS_INLINE cbuf_xxhash(cbuf_t val) {
+ switch (val.len) {
+ case 0:
+ return XXH32_EMPTY_HASH;
+ case 1:
+ return XXH32_ONECHAR_HASH[(uint8_t)val.buf[0]];
+ default:
+ return XXH32(val.buf, val.len, XXH32_SEED);
+ }
+}
+
+static int PANDAS_INLINE cbuf_equal(cbuf_t a, cbuf_t b) {
+ int i;
+ if (a.len != b.len) {
+ return 0;
+ }
+ if (a.buf == b.buf) {
+ return 1;
+ }
+ for (i = 0; i < a.len; ++i) {
+ if (a.buf[i] != b.buf[i]) {
+ return 0;
+ }
+ }
+ return 1;
+}
+
+/* [cbuf_t -> size_t] hash map */
+KHASH_INIT(cbuf_map, cbuf_t, size_t, 1, cbuf_xxhash, cbuf_equal)
+#define kh_exist_cbuf_map(h, k) (kh_exist(h, k))
+
+#endif /* _KLIB_KHASH_PYTHON_H_ */
diff --git a/pandas/src/parser/tokenizer.h b/pandas/src/parser/tokenizer.h
index 0947315fbe6b7..4020dd24c87e8 100644
--- a/pandas/src/parser/tokenizer.h
+++ b/pandas/src/parser/tokenizer.h
@@ -33,7 +33,7 @@ See LICENSE for the license
#include <stdint.h>
#endif
-#include "khash.h"
+#include "khash_python.h"
#define CHUNKSIZE 1024*256
#define KB 1024
diff --git a/pandas/src/xxhash/LICENSE b/pandas/src/xxhash/LICENSE
new file mode 100644
index 0000000000000..7de801ed1bc78
--- /dev/null
+++ b/pandas/src/xxhash/LICENSE
@@ -0,0 +1,24 @@
+xxHash Library
+Copyright (c) 2012-2014, Yann Collet
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice, this
+ list of conditions and the following disclaimer in the documentation and/or
+ other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/pandas/src/xxhash/xxhash.c b/pandas/src/xxhash/xxhash.c
new file mode 100644
index 0000000000000..529d69ccc4caa
--- /dev/null
+++ b/pandas/src/xxhash/xxhash.c
@@ -0,0 +1,934 @@
+/*
+xxHash - Fast Hash algorithm
+Copyright (C) 2012-2014, Yann Collet.
+BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+* Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+You can contact the author at :
+- xxHash source repository : http://code.google.com/p/xxhash/
+- public discussion board : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+
+//**************************************
+// Tuning parameters
+//**************************************
+// Unaligned memory access is automatically enabled for "common" CPU, such as x86.
+// For others CPU, the compiler will be more cautious, and insert extra code to ensure aligned access is respected.
+// If you know your target CPU supports unaligned memory access, you want to force this option manually to improve performance.
+// You can also enable this parameter if you know your input data will always be aligned (boundaries of 4, for U32).
+#if defined(__ARM_FEATURE_UNALIGNED) || defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)
+# define XXH_USE_UNALIGNED_ACCESS 1
+#endif
+
+// XXH_ACCEPT_NULL_INPUT_POINTER :
+// If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer.
+// When this option is enabled, xxHash output for null input pointers will be the same as a null-length input.
+// This option has a very small performance cost (only measurable on small inputs).
+// By default, this option is disabled. To enable it, uncomment below define :
+// #define XXH_ACCEPT_NULL_INPUT_POINTER 1
+
+// XXH_FORCE_NATIVE_FORMAT :
+// By default, xxHash library provides endian-independant Hash values, based on little-endian convention.
+// Results are therefore identical for little-endian and big-endian CPU.
+// This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format.
+// Should endian-independance be of no importance for your application, you may set the #define below to 1.
+// It will improve speed for Big-endian CPU.
+// This option has no impact on Little_Endian CPU.
+#define XXH_FORCE_NATIVE_FORMAT 0
+
+//**************************************
+// Compiler Specific Options
+//**************************************
+// Disable some Visual warning messages
+#ifdef _MSC_VER // Visual Studio
+# pragma warning(disable : 4127) // disable: C4127: conditional expression is constant
+#endif
+
+#ifdef _MSC_VER // Visual Studio
+# define FORCE_INLINE static __forceinline
+#else
+# ifdef __GNUC__
+# define FORCE_INLINE static inline __attribute__((always_inline))
+# else
+# define FORCE_INLINE static inline
+# endif
+#endif
+
+//**************************************
+// Includes & Memory related functions
+//**************************************
+#include "xxhash.h"
+// Modify the local functions below should you wish to use some other memory routines
+// for malloc(), free()
+#include <stdlib.h>
+FORCE_INLINE void* XXH_malloc(size_t s)
+{
+ return malloc(s);
+}
+FORCE_INLINE void XXH_free (void* p)
+{
+ free(p);
+}
+// for memcpy()
+#include <string.h>
+FORCE_INLINE void* XXH_memcpy(void* dest, const void* src, size_t size)
+{
+ return memcpy(dest,src,size);
+}
+
+
+//**************************************
+// Basic Types
+//**************************************
+#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L // C99
+# include <stdint.h>
+typedef uint8_t BYTE;
+typedef uint16_t U16;
+typedef uint32_t U32;
+typedef int32_t S32;
+typedef uint64_t U64;
+#else
+typedef unsigned char BYTE;
+typedef unsigned short U16;
+typedef unsigned int U32;
+typedef signed int S32;
+typedef unsigned long long U64;
+#endif
+
+#if defined(__GNUC__) && !defined(XXH_USE_UNALIGNED_ACCESS)
+# define _PACKED __attribute__ ((packed))
+#else
+# define _PACKED
+#endif
+
+#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__)
+# ifdef __IBMC__
+# pragma pack(1)
+# else
+# pragma pack(push, 1)
+# endif
+#endif
+
+typedef struct _U32_S
+{
+ U32 v;
+} _PACKED U32_S;
+typedef struct _U64_S
+{
+ U64 v;
+} _PACKED U64_S;
+
+#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__)
+# pragma pack(pop)
+#endif
+
+#define A32(x) (((U32_S *)(x))->v)
+#define A64(x) (((U64_S *)(x))->v)
+
+
+//***************************************
+// Compiler-specific Functions and Macros
+//***************************************
+#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+
+// Note : although _rotl exists for minGW (GCC under windows), performance seems poor
+#if defined(_MSC_VER)
+# define XXH_rotl32(x,r) _rotl(x,r)
+# define XXH_rotl64(x,r) _rotl64(x,r)
+#else
+# define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r)))
+# define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r)))
+#endif
+
+#if defined(_MSC_VER) // Visual Studio
+# define XXH_swap32 _byteswap_ulong
+# define XXH_swap64 _byteswap_uint64
+#elif GCC_VERSION >= 403
+# define XXH_swap32 __builtin_bswap32
+# define XXH_swap64 __builtin_bswap64
+#else
+static inline U32 XXH_swap32 (U32 x)
+{
+ return ((x << 24) & 0xff000000 ) |
+ ((x << 8) & 0x00ff0000 ) |
+ ((x >> 8) & 0x0000ff00 ) |
+ ((x >> 24) & 0x000000ff );
+}
+static inline U64 XXH_swap64 (U64 x)
+{
+ return ((x << 56) & 0xff00000000000000ULL) |
+ ((x << 40) & 0x00ff000000000000ULL) |
+ ((x << 24) & 0x0000ff0000000000ULL) |
+ ((x << 8) & 0x000000ff00000000ULL) |
+ ((x >> 8) & 0x00000000ff000000ULL) |
+ ((x >> 24) & 0x0000000000ff0000ULL) |
+ ((x >> 40) & 0x000000000000ff00ULL) |
+ ((x >> 56) & 0x00000000000000ffULL);
+}
+#endif
+
+
+//**************************************
+// Constants
+//**************************************
+#define PRIME32_1 2654435761U
+#define PRIME32_2 2246822519U
+#define PRIME32_3 3266489917U
+#define PRIME32_4 668265263U
+#define PRIME32_5 374761393U
+
+#define PRIME64_1 11400714785074694791ULL
+#define PRIME64_2 14029467366897019727ULL
+#define PRIME64_3 1609587929392839161ULL
+#define PRIME64_4 9650029242287828579ULL
+#define PRIME64_5 2870177450012600261ULL
+
+//**************************************
+// Architecture Macros
+//**************************************
+typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess;
+#ifndef XXH_CPU_LITTLE_ENDIAN // It is possible to define XXH_CPU_LITTLE_ENDIAN externally, for example using a compiler switch
+static const int one = 1;
+# define XXH_CPU_LITTLE_ENDIAN (*(char*)(&one))
+#endif
+
+
+//**************************************
+// Macros
+//**************************************
+#define XXH_STATIC_ASSERT(c) { enum { XXH_static_assert = 1/(!!(c)) }; } // use only *after* variable declarations
+
+
+//****************************
+// Memory reads
+//****************************
+typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment;
+
+FORCE_INLINE U32 XXH_readLE32_align(const U32* ptr, XXH_endianess endian, XXH_alignment align)
+{
+ if (align==XXH_unaligned)
+ return endian==XXH_littleEndian ? A32(ptr) : XXH_swap32(A32(ptr));
+ else
+ return endian==XXH_littleEndian ? *ptr : XXH_swap32(*ptr);
+}
+
+FORCE_INLINE U32 XXH_readLE32(const U32* ptr, XXH_endianess endian)
+{
+ return XXH_readLE32_align(ptr, endian, XXH_unaligned);
+}
+
+FORCE_INLINE U64 XXH_readLE64_align(const U64* ptr, XXH_endianess endian, XXH_alignment align)
+{
+ if (align==XXH_unaligned)
+ return endian==XXH_littleEndian ? A64(ptr) : XXH_swap64(A64(ptr));
+ else
+ return endian==XXH_littleEndian ? *ptr : XXH_swap64(*ptr);
+}
+
+FORCE_INLINE U64 XXH_readLE64(const U64* ptr, XXH_endianess endian)
+{
+ return XXH_readLE64_align(ptr, endian, XXH_unaligned);
+}
+
+
+//****************************
+// Simple Hash Functions
+//****************************
+FORCE_INLINE U32 XXH32_endian_align(const void* input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align)
+{
+ const BYTE* p = (const BYTE*)input;
+ const BYTE* bEnd = p + len;
+ U32 h32;
+#define XXH_get32bits(p) XXH_readLE32_align((const U32*)p, endian, align)
+
+#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
+ if (p==NULL)
+ {
+ len=0;
+ bEnd=p=(const BYTE*)(size_t)16;
+ }
+#endif
+
+ if (len>=16)
+ {
+ const BYTE* const limit = bEnd - 16;
+ U32 v1 = seed + PRIME32_1 + PRIME32_2;
+ U32 v2 = seed + PRIME32_2;
+ U32 v3 = seed + 0;
+ U32 v4 = seed - PRIME32_1;
+
+ do
+ {
+ v1 += XXH_get32bits(p) * PRIME32_2;
+ v1 = XXH_rotl32(v1, 13);
+ v1 *= PRIME32_1;
+ p+=4;
+ v2 += XXH_get32bits(p) * PRIME32_2;
+ v2 = XXH_rotl32(v2, 13);
+ v2 *= PRIME32_1;
+ p+=4;
+ v3 += XXH_get32bits(p) * PRIME32_2;
+ v3 = XXH_rotl32(v3, 13);
+ v3 *= PRIME32_1;
+ p+=4;
+ v4 += XXH_get32bits(p) * PRIME32_2;
+ v4 = XXH_rotl32(v4, 13);
+ v4 *= PRIME32_1;
+ p+=4;
+ }
+ while (p<=limit);
+
+ h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18);
+ }
+ else
+ {
+ h32 = seed + PRIME32_5;
+ }
+
+ h32 += (U32) len;
+
+ while (p+4<=bEnd)
+ {
+ h32 += XXH_get32bits(p) * PRIME32_3;
+ h32 = XXH_rotl32(h32, 17) * PRIME32_4 ;
+ p+=4;
+ }
+
+ while (p<bEnd)
+ {
+ h32 += (*p) * PRIME32_5;
+ h32 = XXH_rotl32(h32, 11) * PRIME32_1 ;
+ p++;
+ }
+
+ h32 ^= h32 >> 15;
+ h32 *= PRIME32_2;
+ h32 ^= h32 >> 13;
+ h32 *= PRIME32_3;
+ h32 ^= h32 >> 16;
+
+ return h32;
+}
+
+
+unsigned int XXH32 (const void* input, size_t len, unsigned seed)
+{
+#if 0
+ // Simple version, good for code maintenance, but unfortunately slow for small inputs
+ XXH32_state_t state;
+ XXH32_reset(&state, seed);
+ XXH32_update(&state, input, len);
+ return XXH32_digest(&state);
+#else
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+# if !defined(XXH_USE_UNALIGNED_ACCESS)
+ if ((((size_t)input) & 3) == 0) // Input is aligned, let's leverage the speed advantage
+ {
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);
+ else
+ return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);
+ }
+# endif
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);
+ else
+ return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);
+#endif
+}
+
+FORCE_INLINE U64 XXH64_endian_align(const void* input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align)
+{
+ const BYTE* p = (const BYTE*)input;
+ const BYTE* bEnd = p + len;
+ U64 h64;
+#define XXH_get64bits(p) XXH_readLE64_align((const U64*)p, endian, align)
+
+#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
+ if (p==NULL)
+ {
+ len=0;
+ bEnd=p=(const BYTE*)(size_t)32;
+ }
+#endif
+
+ if (len>=32)
+ {
+ const BYTE* const limit = bEnd - 32;
+ U64 v1 = seed + PRIME64_1 + PRIME64_2;
+ U64 v2 = seed + PRIME64_2;
+ U64 v3 = seed + 0;
+ U64 v4 = seed - PRIME64_1;
+
+ do
+ {
+ v1 += XXH_get64bits(p) * PRIME64_2;
+ p+=8;
+ v1 = XXH_rotl64(v1, 31);
+ v1 *= PRIME64_1;
+ v2 += XXH_get64bits(p) * PRIME64_2;
+ p+=8;
+ v2 = XXH_rotl64(v2, 31);
+ v2 *= PRIME64_1;
+ v3 += XXH_get64bits(p) * PRIME64_2;
+ p+=8;
+ v3 = XXH_rotl64(v3, 31);
+ v3 *= PRIME64_1;
+ v4 += XXH_get64bits(p) * PRIME64_2;
+ p+=8;
+ v4 = XXH_rotl64(v4, 31);
+ v4 *= PRIME64_1;
+ }
+ while (p<=limit);
+
+ h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);
+
+ v1 *= PRIME64_2;
+ v1 = XXH_rotl64(v1, 31);
+ v1 *= PRIME64_1;
+ h64 ^= v1;
+ h64 = h64 * PRIME64_1 + PRIME64_4;
+
+ v2 *= PRIME64_2;
+ v2 = XXH_rotl64(v2, 31);
+ v2 *= PRIME64_1;
+ h64 ^= v2;
+ h64 = h64 * PRIME64_1 + PRIME64_4;
+
+ v3 *= PRIME64_2;
+ v3 = XXH_rotl64(v3, 31);
+ v3 *= PRIME64_1;
+ h64 ^= v3;
+ h64 = h64 * PRIME64_1 + PRIME64_4;
+
+ v4 *= PRIME64_2;
+ v4 = XXH_rotl64(v4, 31);
+ v4 *= PRIME64_1;
+ h64 ^= v4;
+ h64 = h64 * PRIME64_1 + PRIME64_4;
+ }
+ else
+ {
+ h64 = seed + PRIME64_5;
+ }
+
+ h64 += (U64) len;
+
+ while (p+8<=bEnd)
+ {
+ U64 k1 = XXH_get64bits(p);
+ k1 *= PRIME64_2;
+ k1 = XXH_rotl64(k1,31);
+ k1 *= PRIME64_1;
+ h64 ^= k1;
+ h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4;
+ p+=8;
+ }
+
+ if (p+4<=bEnd)
+ {
+ h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1;
+ h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3;
+ p+=4;
+ }
+
+ while (p<bEnd)
+ {
+ h64 ^= (*p) * PRIME64_5;
+ h64 = XXH_rotl64(h64, 11) * PRIME64_1;
+ p++;
+ }
+
+ h64 ^= h64 >> 33;
+ h64 *= PRIME64_2;
+ h64 ^= h64 >> 29;
+ h64 *= PRIME64_3;
+ h64 ^= h64 >> 32;
+
+ return h64;
+}
+
+
+unsigned long long XXH64 (const void* input, size_t len, unsigned long long seed)
+{
+#if 0
+ // Simple version, good for code maintenance, but unfortunately slow for small inputs
+ XXH64_state_t state;
+ XXH64_reset(&state, seed);
+ XXH64_update(&state, input, len);
+ return XXH64_digest(&state);
+#else
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+# if !defined(XXH_USE_UNALIGNED_ACCESS)
+ if ((((size_t)input) & 7)==0) // Input is aligned, let's leverage the speed advantage
+ {
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);
+ else
+ return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);
+ }
+# endif
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);
+ else
+ return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);
+#endif
+}
+
+/****************************************************
+ * Advanced Hash Functions
+****************************************************/
+
+/*** Allocation ***/
+typedef struct
+{
+ U64 total_len;
+ U32 seed;
+ U32 v1;
+ U32 v2;
+ U32 v3;
+ U32 v4;
+ U32 memsize;
+ char memory[16];
+} XXH_istate32_t;
+
+typedef struct
+{
+ U64 total_len;
+ U64 seed;
+ U64 v1;
+ U64 v2;
+ U64 v3;
+ U64 v4;
+ U32 memsize;
+ char memory[32];
+} XXH_istate64_t;
+
+
+XXH32_state_t* XXH32_createState(void)
+{
+ XXH_STATIC_ASSERT(sizeof(XXH32_state_t) >= sizeof(XXH_istate32_t)); // A compilation error here means XXH32_state_t is not large enough
+ return (XXH32_state_t*)malloc(sizeof(XXH32_state_t));
+}
+XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr)
+{
+ free(statePtr);
+ return XXH_OK;
+};
+
+XXH64_state_t* XXH64_createState(void)
+{
+ XXH_STATIC_ASSERT(sizeof(XXH64_state_t) >= sizeof(XXH_istate64_t)); // A compilation error here means XXH64_state_t is not large enough
+ return (XXH64_state_t*)malloc(sizeof(XXH64_state_t));
+}
+XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr)
+{
+ free(statePtr);
+ return XXH_OK;
+};
+
+
+/*** Hash feed ***/
+
+XXH_errorcode XXH32_reset(XXH32_state_t* state_in, U32 seed)
+{
+ XXH_istate32_t* state = (XXH_istate32_t*) state_in;
+ state->seed = seed;
+ state->v1 = seed + PRIME32_1 + PRIME32_2;
+ state->v2 = seed + PRIME32_2;
+ state->v3 = seed + 0;
+ state->v4 = seed - PRIME32_1;
+ state->total_len = 0;
+ state->memsize = 0;
+ return XXH_OK;
+}
+
+XXH_errorcode XXH64_reset(XXH64_state_t* state_in, unsigned long long seed)
+{
+ XXH_istate64_t* state = (XXH_istate64_t*) state_in;
+ state->seed = seed;
+ state->v1 = seed + PRIME64_1 + PRIME64_2;
+ state->v2 = seed + PRIME64_2;
+ state->v3 = seed + 0;
+ state->v4 = seed - PRIME64_1;
+ state->total_len = 0;
+ state->memsize = 0;
+ return XXH_OK;
+}
+
+
+FORCE_INLINE XXH_errorcode XXH32_update_endian (XXH32_state_t* state_in, const void* input, size_t len, XXH_endianess endian)
+{
+ XXH_istate32_t* state = (XXH_istate32_t *) state_in;
+ const BYTE* p = (const BYTE*)input;
+ const BYTE* const bEnd = p + len;
+
+#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
+ if (input==NULL) return XXH_ERROR;
+#endif
+
+ state->total_len += len;
+
+ if (state->memsize + len < 16) // fill in tmp buffer
+ {
+ XXH_memcpy(state->memory + state->memsize, input, len);
+ state->memsize += (U32)len;
+ return XXH_OK;
+ }
+
+ if (state->memsize) // some data left from previous update
+ {
+ XXH_memcpy(state->memory + state->memsize, input, 16-state->memsize);
+ {
+ const U32* p32 = (const U32*)state->memory;
+ state->v1 += XXH_readLE32(p32, endian) * PRIME32_2;
+ state->v1 = XXH_rotl32(state->v1, 13);
+ state->v1 *= PRIME32_1;
+ p32++;
+ state->v2 += XXH_readLE32(p32, endian) * PRIME32_2;
+ state->v2 = XXH_rotl32(state->v2, 13);
+ state->v2 *= PRIME32_1;
+ p32++;
+ state->v3 += XXH_readLE32(p32, endian) * PRIME32_2;
+ state->v3 = XXH_rotl32(state->v3, 13);
+ state->v3 *= PRIME32_1;
+ p32++;
+ state->v4 += XXH_readLE32(p32, endian) * PRIME32_2;
+ state->v4 = XXH_rotl32(state->v4, 13);
+ state->v4 *= PRIME32_1;
+ p32++;
+ }
+ p += 16-state->memsize;
+ state->memsize = 0;
+ }
+
+ if (p <= bEnd-16)
+ {
+ const BYTE* const limit = bEnd - 16;
+ U32 v1 = state->v1;
+ U32 v2 = state->v2;
+ U32 v3 = state->v3;
+ U32 v4 = state->v4;
+
+ do
+ {
+ v1 += XXH_readLE32((const U32*)p, endian) * PRIME32_2;
+ v1 = XXH_rotl32(v1, 13);
+ v1 *= PRIME32_1;
+ p+=4;
+ v2 += XXH_readLE32((const U32*)p, endian) * PRIME32_2;
+ v2 = XXH_rotl32(v2, 13);
+ v2 *= PRIME32_1;
+ p+=4;
+ v3 += XXH_readLE32((const U32*)p, endian) * PRIME32_2;
+ v3 = XXH_rotl32(v3, 13);
+ v3 *= PRIME32_1;
+ p+=4;
+ v4 += XXH_readLE32((const U32*)p, endian) * PRIME32_2;
+ v4 = XXH_rotl32(v4, 13);
+ v4 *= PRIME32_1;
+ p+=4;
+ }
+ while (p<=limit);
+
+ state->v1 = v1;
+ state->v2 = v2;
+ state->v3 = v3;
+ state->v4 = v4;
+ }
+
+ if (p < bEnd)
+ {
+ XXH_memcpy(state->memory, p, bEnd-p);
+ state->memsize = (int)(bEnd-p);
+ }
+
+ return XXH_OK;
+}
+
+XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len)
+{
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH32_update_endian(state_in, input, len, XXH_littleEndian);
+ else
+ return XXH32_update_endian(state_in, input, len, XXH_bigEndian);
+}
+
+
+
+FORCE_INLINE U32 XXH32_digest_endian (const XXH32_state_t* state_in, XXH_endianess endian)
+{
+ XXH_istate32_t* state = (XXH_istate32_t*) state_in;
+ const BYTE * p = (const BYTE*)state->memory;
+ BYTE* bEnd = (BYTE*)state->memory + state->memsize;
+ U32 h32;
+
+ if (state->total_len >= 16)
+ {
+ h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18);
+ }
+ else
+ {
+ h32 = state->seed + PRIME32_5;
+ }
+
+ h32 += (U32) state->total_len;
+
+ while (p+4<=bEnd)
+ {
+ h32 += XXH_readLE32((const U32*)p, endian) * PRIME32_3;
+ h32 = XXH_rotl32(h32, 17) * PRIME32_4;
+ p+=4;
+ }
+
+ while (p<bEnd)
+ {
+ h32 += (*p) * PRIME32_5;
+ h32 = XXH_rotl32(h32, 11) * PRIME32_1;
+ p++;
+ }
+
+ h32 ^= h32 >> 15;
+ h32 *= PRIME32_2;
+ h32 ^= h32 >> 13;
+ h32 *= PRIME32_3;
+ h32 ^= h32 >> 16;
+
+ return h32;
+}
+
+
+U32 XXH32_digest (const XXH32_state_t* state_in)
+{
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH32_digest_endian(state_in, XXH_littleEndian);
+ else
+ return XXH32_digest_endian(state_in, XXH_bigEndian);
+}
+
+
+FORCE_INLINE XXH_errorcode XXH64_update_endian (XXH64_state_t* state_in, const void* input, size_t len, XXH_endianess endian)
+{
+ XXH_istate64_t * state = (XXH_istate64_t *) state_in;
+ const BYTE* p = (const BYTE*)input;
+ const BYTE* const bEnd = p + len;
+
+#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
+ if (input==NULL) return XXH_ERROR;
+#endif
+
+ state->total_len += len;
+
+ if (state->memsize + len < 32) // fill in tmp buffer
+ {
+ XXH_memcpy(state->memory + state->memsize, input, len);
+ state->memsize += (U32)len;
+ return XXH_OK;
+ }
+
+ if (state->memsize) // some data left from previous update
+ {
+ XXH_memcpy(state->memory + state->memsize, input, 32-state->memsize);
+ {
+ const U64* p64 = (const U64*)state->memory;
+ state->v1 += XXH_readLE64(p64, endian) * PRIME64_2;
+ state->v1 = XXH_rotl64(state->v1, 31);
+ state->v1 *= PRIME64_1;
+ p64++;
+ state->v2 += XXH_readLE64(p64, endian) * PRIME64_2;
+ state->v2 = XXH_rotl64(state->v2, 31);
+ state->v2 *= PRIME64_1;
+ p64++;
+ state->v3 += XXH_readLE64(p64, endian) * PRIME64_2;
+ state->v3 = XXH_rotl64(state->v3, 31);
+ state->v3 *= PRIME64_1;
+ p64++;
+ state->v4 += XXH_readLE64(p64, endian) * PRIME64_2;
+ state->v4 = XXH_rotl64(state->v4, 31);
+ state->v4 *= PRIME64_1;
+ p64++;
+ }
+ p += 32-state->memsize;
+ state->memsize = 0;
+ }
+
+ if (p+32 <= bEnd)
+ {
+ const BYTE* const limit = bEnd - 32;
+ U64 v1 = state->v1;
+ U64 v2 = state->v2;
+ U64 v3 = state->v3;
+ U64 v4 = state->v4;
+
+ do
+ {
+ v1 += XXH_readLE64((const U64*)p, endian) * PRIME64_2;
+ v1 = XXH_rotl64(v1, 31);
+ v1 *= PRIME64_1;
+ p+=8;
+ v2 += XXH_readLE64((const U64*)p, endian) * PRIME64_2;
+ v2 = XXH_rotl64(v2, 31);
+ v2 *= PRIME64_1;
+ p+=8;
+ v3 += XXH_readLE64((const U64*)p, endian) * PRIME64_2;
+ v3 = XXH_rotl64(v3, 31);
+ v3 *= PRIME64_1;
+ p+=8;
+ v4 += XXH_readLE64((const U64*)p, endian) * PRIME64_2;
+ v4 = XXH_rotl64(v4, 31);
+ v4 *= PRIME64_1;
+ p+=8;
+ }
+ while (p<=limit);
+
+ state->v1 = v1;
+ state->v2 = v2;
+ state->v3 = v3;
+ state->v4 = v4;
+ }
+
+ if (p < bEnd)
+ {
+ XXH_memcpy(state->memory, p, bEnd-p);
+ state->memsize = (int)(bEnd-p);
+ }
+
+ return XXH_OK;
+}
+
+XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len)
+{
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH64_update_endian(state_in, input, len, XXH_littleEndian);
+ else
+ return XXH64_update_endian(state_in, input, len, XXH_bigEndian);
+}
+
+
+
+FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state_in, XXH_endianess endian)
+{
+ XXH_istate64_t * state = (XXH_istate64_t *) state_in;
+ const BYTE * p = (const BYTE*)state->memory;
+ BYTE* bEnd = (BYTE*)state->memory + state->memsize;
+ U64 h64;
+
+ if (state->total_len >= 32)
+ {
+ U64 v1 = state->v1;
+ U64 v2 = state->v2;
+ U64 v3 = state->v3;
+ U64 v4 = state->v4;
+
+ h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);
+
+ v1 *= PRIME64_2;
+ v1 = XXH_rotl64(v1, 31);
+ v1 *= PRIME64_1;
+ h64 ^= v1;
+ h64 = h64*PRIME64_1 + PRIME64_4;
+
+ v2 *= PRIME64_2;
+ v2 = XXH_rotl64(v2, 31);
+ v2 *= PRIME64_1;
+ h64 ^= v2;
+ h64 = h64*PRIME64_1 + PRIME64_4;
+
+ v3 *= PRIME64_2;
+ v3 = XXH_rotl64(v3, 31);
+ v3 *= PRIME64_1;
+ h64 ^= v3;
+ h64 = h64*PRIME64_1 + PRIME64_4;
+
+ v4 *= PRIME64_2;
+ v4 = XXH_rotl64(v4, 31);
+ v4 *= PRIME64_1;
+ h64 ^= v4;
+ h64 = h64*PRIME64_1 + PRIME64_4;
+ }
+ else
+ {
+ h64 = state->seed + PRIME64_5;
+ }
+
+ h64 += (U64) state->total_len;
+
+ while (p+8<=bEnd)
+ {
+ U64 k1 = XXH_readLE64((const U64*)p, endian);
+ k1 *= PRIME64_2;
+ k1 = XXH_rotl64(k1,31);
+ k1 *= PRIME64_1;
+ h64 ^= k1;
+ h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4;
+ p+=8;
+ }
+
+ if (p+4<=bEnd)
+ {
+ h64 ^= (U64)(XXH_readLE32((const U32*)p, endian)) * PRIME64_1;
+ h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3;
+ p+=4;
+ }
+
+ while (p<bEnd)
+ {
+ h64 ^= (*p) * PRIME64_5;
+ h64 = XXH_rotl64(h64, 11) * PRIME64_1;
+ p++;
+ }
+
+ h64 ^= h64 >> 33;
+ h64 *= PRIME64_2;
+ h64 ^= h64 >> 29;
+ h64 *= PRIME64_3;
+ h64 ^= h64 >> 32;
+
+ return h64;
+}
+
+
+unsigned long long XXH64_digest (const XXH64_state_t* state_in)
+{
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH64_digest_endian(state_in, XXH_littleEndian);
+ else
+ return XXH64_digest_endian(state_in, XXH_bigEndian);
+}
+
+
diff --git a/pandas/src/xxhash/xxhash.h b/pandas/src/xxhash/xxhash.h
new file mode 100644
index 0000000000000..55b45015a447e
--- /dev/null
+++ b/pandas/src/xxhash/xxhash.h
@@ -0,0 +1,156 @@
+/*
+ xxHash - Extremely Fast Hash algorithm
+ Header File
+ Copyright (C) 2012-2014, Yann Collet.
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ You can contact the author at :
+ - xxHash source repository : http://code.google.com/p/xxhash/
+*/
+
+/* Notice extracted from xxHash homepage :
+
+xxHash is an extremely fast Hash algorithm, running at RAM speed limits.
+It also successfully passes all tests from the SMHasher suite.
+
+Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz)
+
+Name Speed Q.Score Author
+xxHash 5.4 GB/s 10
+CrapWow 3.2 GB/s 2 Andrew
+MumurHash 3a 2.7 GB/s 10 Austin Appleby
+SpookyHash 2.0 GB/s 10 Bob Jenkins
+SBox 1.4 GB/s 9 Bret Mulvey
+Lookup3 1.2 GB/s 9 Bob Jenkins
+SuperFastHash 1.2 GB/s 1 Paul Hsieh
+CityHash64 1.05 GB/s 10 Pike & Alakuijala
+FNV 0.55 GB/s 5 Fowler, Noll, Vo
+CRC32 0.43 GB/s 9
+MD5-32 0.33 GB/s 10 Ronald L. Rivest
+SHA1-32 0.28 GB/s 10
+
+Q.Score is a measure of quality of the hash function.
+It depends on successfully passing SMHasher test set.
+10 is a perfect score.
+*/
+
+#pragma once
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+
+/*****************************
+ Includes
+*****************************/
+#include <stddef.h> /* size_t */
+
+
+/*****************************
+ Type
+*****************************/
+typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode;
+
+
+
+/*****************************
+ Simple Hash Functions
+*****************************/
+
+unsigned int XXH32 (const void* input, size_t length, unsigned seed);
+unsigned long long XXH64 (const void* input, size_t length, unsigned long long seed);
+
+/*
+XXH32() :
+ Calculate the 32-bits hash of sequence "length" bytes stored at memory address "input".
+ The memory between input & input+length must be valid (allocated and read-accessible).
+ "seed" can be used to alter the result predictably.
+ This function successfully passes all SMHasher tests.
+ Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s
+XXH64() :
+ Calculate the 64-bits hash of sequence of length "len" stored at memory address "input".
+*/
+
+
+
+/*****************************
+ Advanced Hash Functions
+*****************************/
+typedef struct { long long ll[ 6]; } XXH32_state_t;
+typedef struct { long long ll[11]; } XXH64_state_t;
+
+/*
+These structures allow static allocation of XXH states.
+States must then be initialized using XXHnn_reset() before first use.
+
+If you prefer dynamic allocation, please refer to functions below.
+*/
+
+XXH32_state_t* XXH32_createState(void);
+XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr);
+
+XXH64_state_t* XXH64_createState(void);
+XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr);
+
+/*
+These functions create and release memory for XXH state.
+States must then be initialized using XXHnn_reset() before first use.
+*/
+
+
+XXH_errorcode XXH32_reset (XXH32_state_t* statePtr, unsigned seed);
+XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length);
+unsigned int XXH32_digest (const XXH32_state_t* statePtr);
+
+XXH_errorcode XXH64_reset (XXH64_state_t* statePtr, unsigned long long seed);
+XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length);
+unsigned long long XXH64_digest (const XXH64_state_t* statePtr);
+
+/*
+These functions calculate the xxHash of an input provided in multiple smaller packets,
+as opposed to an input provided as a single block.
+
+XXH state space must first be allocated, using either static or dynamic method provided above.
+
+Start a new hash by initializing state with a seed, using XXHnn_reset().
+
+Then, feed the hash state by calling XXHnn_update() as many times as necessary.
+Obviously, input must be valid, meaning allocated and read accessible.
+The function returns an error code, with 0 meaning OK, and any other value meaning there is an error.
+
+Finally, you can produce a hash anytime, by using XXHnn_digest().
+This function returns the final nn-bits hash.
+You can nonetheless continue feeding the hash state with more input,
+and therefore get some new hashes, by calling again XXHnn_digest().
+
+When you are done, don't forget to free XXH state space, using typically XXHnn_freeState().
+*/
+
+
+#if defined (__cplusplus)
+}
+#endif
diff --git a/setup.py b/setup.py
index a14f831613696..f9fbdae83d233 100755
--- a/setup.py
+++ b/setup.py
@@ -275,7 +275,7 @@ def initialize_options(self):
'JSONtoObj.c',
'ultrajsonenc.c',
'ultrajsondec.c',
- ]
+ 'xxhash.c']
for root, dirs, files in os.walk('pandas'):
for f in files:
@@ -452,7 +452,11 @@ def pxd(name):
'pxdfiles': [],
'depends': lib_depends},
hashtable={'pyxfile': 'hashtable',
- 'pxdfiles': ['hashtable']},
+ 'pxdfiles': ['hashtable'],
+ 'depends': ['pandas/src/xxhash/xxhash.h',
+ 'pandas/src/klib/khash_python.h',
+ 'pandas/src/klib/khash.h'],
+ 'sources': ['pandas/src/xxhash/xxhash.c']},
tslib={'pyxfile': 'tslib',
'depends': tseries_depends,
'sources': ['pandas/src/datetime/np_datetime.c',
@@ -467,9 +471,14 @@ def pxd(name):
parser=dict(pyxfile='parser',
depends=['pandas/src/parser/tokenizer.h',
'pandas/src/parser/io.h',
- 'pandas/src/numpy_helper.h'],
+ 'pandas/src/numpy_helper.h',
+ 'pandas/src/xxhash/xxhash.h',
+ 'pandas/src/klib/khash_python.h',
+ 'pandas/src/klib/khash.h'],
sources=['pandas/src/parser/tokenizer.c',
- 'pandas/src/parser/io.c'])
+ 'pandas/src/parser/io.c',
+ 'pandas/src/xxhash/xxhash.c'],
+ libraries=['hashtable'])
)
extensions = []
diff --git a/vb_suite/factorize.py b/vb_suite/factorize.py
new file mode 100644
index 0000000000000..21ce350d91262
--- /dev/null
+++ b/vb_suite/factorize.py
@@ -0,0 +1,62 @@
+from vbench.api import Benchmark
+from datetime import datetime
+
+START_DATE = datetime(2014, 10, 13)
+
+# GH 8524
+
+common_setup = """from pandas_vb_common import *
+from pandas import factorize
+SIZE = 1000000
+indices = np.random.randint(100, size=SIZE)
+"""
+
+
+# --- Integer array factorization
+setup = common_setup + """
+int_values_uniq = np.arange(SIZE) * 100
+"""
+factorize_int_uniq = Benchmark("factorize(int_values_uniq)", setup,
+ start_date=START_DATE)
+setup = common_setup + """
+int_values_dup = (np.arange(SIZE) * 100).take(indices)
+"""
+factorize_int_dup = Benchmark("factorize(int_values_dup)", setup,
+ start_date=START_DATE)
+
+
+# --- String array factorization
+setup = common_setup + """
+str_values_uniq = tm.makeStringIndex(SIZE)
+"""
+factorize_str_uniq = Benchmark("factorize(str_values_uniq)", setup=setup,
+ start_date=START_DATE)
+setup = common_setup + """
+str_values_dup = tm.makeStringIndex(SIZE).take(indices)
+"""
+factorize_str_dup = Benchmark("factorize(str_values_dup)", setup=setup,
+ start_date=START_DATE)
+setup = common_setup + """
+shortstr_4_dup = Index(np.take(['AA', 'BB', 'CC', 'DD'],
+ np.random.randint(4, size=SIZE)))
+"""
+factorize_shortstr_4_dup = Benchmark("factorize(shortstr_values_dup)",
+ setup=setup, start_date=START_DATE)
+setup = common_setup + """
+shortstr_many_dup = tm.rands_array(2, SIZE)
+"""
+factorize_shortstr_many_dup = Benchmark("factorize(shortstr_many_dup)",
+ setup=setup, start_date=START_DATE)
+
+
+# --- Float array factorization
+setup = common_setup + """
+float_values_uniq = np.linspace(0., 1., num=SIZE) * 100
+"""
+factorize_float_uniq = Benchmark("factorize(float_values_uniq)", setup=setup,
+ start_date=START_DATE)
+setup = common_setup + """
+float_values_dup = (np.linspace(0., 1., num=SIZE) * 100).take(indices)
+"""
+factorize_float_dup = Benchmark("factorize(float_values_dup)", setup,
+ start_date=START_DATE)
diff --git a/vb_suite/suite.py b/vb_suite/suite.py
index a16d183ae62e2..e9d325d2ef543 100644
--- a/vb_suite/suite.py
+++ b/vb_suite/suite.py
@@ -6,6 +6,7 @@
modules = ['attrs_caching',
'binary_ops',
'ctors',
+ 'factorize',
'frame_ctor',
'frame_methods',
'groupby',
| This should close #8524.
The idea is that quadratic probing `(i**2 + i)/2` is faster than double hashing and can be shown to traverse all elements if `nbuckets == 2**N`.
This branch compiles and passes tests, but I haven't done any benchmarks yet.
## TODO
(probably in other issues)
- [ ] see if the "flag compression" hack can be removed, it complicates syncing and
I'm not sure if there was any noticeable performance increase
- [x] request upstream klib maintainers to add a way to override "kh_inline",
e.g. by wrapping its definition with `#ifndef kh_inline`, so that
`PANDAS_INLINE` flag can be moved away from khash.h and specified in
`khash_python.h" with
``` c
#define kh_inline PANDAS_INLINE
#include "khash.h"
```
- [ ] I don't like it that pandas makes `khint64_t` definition signed. In
upstream it is unsigned which -- I agree -- is inconsistent, but bit shifting
operations on signed integers have a) undefined behaviour according to the
standard and b) different semantics which might cause performance degradation
on some hash functions:
``` c
int main(int argc, char *argv[])
{
int64_t foo = -1;
uint64_t ufoo = *((uint64_t*)&foo);
printf("foo: %lx; foo>>1: %lx\n", foo, foo >> 1);
printf("ufoo: %lx; ufoo>>1: %lx\n", ufoo, ufoo >> 1);
return 0;
}
```
```
$ ./a.out
foo: ffffffffffffffff; foo>>1: ffffffffffffffff
ufoo: ffffffffffffffff; ufoo>>1: 7fffffffffffffff
```
- [ ] memory allocation functions `kmalloc/krealloc/kfree` should be overridden to
use PyMem interface to be shown in tracemalloc output. `PyMem_Calloc` is
[only provided for 3.5](http://bugs.python.org/issue21233), so it may require more work than just defining a macro
rename.
- [ ] khash-0.2.8 API introduces `-1` return values for operations that have failed,
most likely because of memory allocation errors. these should be handled and
reported as `MemoryError`s to the interpreter
| https://api.github.com/repos/pandas-dev/pandas/pulls/8547 | 2014-10-13T08:18:02Z | 2015-05-09T16:07:17Z | null | 2022-10-13T00:16:10Z |
PERF: Performance improvement for MultiIndexes with a DatetimeIndex levels | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 9735202327d3b..ff96df1d087a9 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -932,6 +932,7 @@ Performance
- Performance improvement in writing to sql (``to_sql``) of up to 50% (:issue:`8208`).
- Performance benchmarking of groupby for large value of ngroups (:issue:`6787`)
- Performance improvement in ``CustomBusinessDay``, ``CustomBusinessMonth`` (:issue:`8236`)
+- Performance improvement for ``MultiIndex.values`` for multi-level indexes containing datetimes (:issue:`8543`)
diff --git a/pandas/core/index.py b/pandas/core/index.py
index b9f1a06b171ed..919018977cb80 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -2937,10 +2937,11 @@ def values(self):
values = []
for lev, lab in zip(self.levels, self.labels):
- taken = com.take_1d(lev.values, lab)
+ lev_values = lev.values
# Need to box timestamps, etc.
if hasattr(lev, '_box_values'):
- taken = lev._box_values(taken)
+ lev_values = lev._box_values(lev_values)
+ taken = com.take_1d(lev_values, lab)
values.append(taken)
self._tuples = lib.fast_zip(values)
diff --git a/vb_suite/index_object.py b/vb_suite/index_object.py
index 5ddb2fb0ac7ec..de60a44e23a52 100644
--- a/vb_suite/index_object.py
+++ b/vb_suite/index_object.py
@@ -117,3 +117,16 @@
multiindex_from_product = Benchmark('MultiIndex.from_product(iterables)',
setup, name='multiindex_from_product',
start_date=datetime(2014, 6, 30))
+
+#----------------------------------------------------------------------
+# MultiIndex with DatetimeIndex level
+
+setup = common_setup + """
+level1 = range(1000)
+level2 = date_range(start='1/1/2012', periods=10)
+"""
+
+multiindex_with_datetime_level = \
+ Benchmark("MultiIndex.from_product([level1, level2]).values", setup,
+ name='multiindex_with_datetime_level',
+ start_date=datetime(2014, 10, 11))
| Addresses #8543. The benefits are most pronounced when there are a small number of distinct datetimes relative to the number of rows in the index.
vbench results with `-r multi`:
```
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
multi_with_datetime_level | 1.5767 | 46.8633 | 0.0336 |
reindex_multiindex | 1.1919 | 1.2113 | 0.9840 |
groupby_transform_multi_key4 | 121.5626 | 123.5036 | 0.9843 |
frame_multi_and_st | 33.3813 | 33.5990 | 0.9935 |
groupby_multi_series_op | 11.2731 | 11.3403 | 0.9941 |
groupby_multi_count | 7.2227 | 7.2653 | 0.9941 |
groupby_multi_different_functions | 9.5117 | 9.5397 | 0.9971 |
groupby_multi_size | 19.4443 | 19.4850 | 0.9979 |
frame_multi_and_no_ne | 55.7680 | 55.8747 | 0.9981 |
groupby_multi_different_numpy_functions | 9.5197 | 9.5037 | 1.0017 |
groupby_transform_multi_key1 | 65.6123 | 65.4763 | 1.0021 |
read_table_multiple_date | 148.9107 | 148.2257 | 1.0046 |
join_dataframe_index_multi | 15.1207 | 15.0447 | 1.0051 |
stat_ops_level_frame_sum_multiple | 6.7097 | 6.6660 | 1.0065 |
groupby_multi_cython | 12.6956 | 12.5817 | 1.0091 |
frame_multi_and | 19.6610 | 19.4677 | 1.0099 |
read_table_multiple_date_baseline | 68.1753 | 67.3580 | 1.0121 |
multiindex_from_product | 10.0873 | 9.9500 | 1.0138 |
groupby_transform_multi_key2 | 45.2770 | 44.5527 | 1.0163 |
groupby_multi_python | 122.5337 | 119.1190 | 1.0287 |
stat_ops_level_series_sum_multiple | 5.2770 | 5.1050 | 1.0337 |
groupby_transform_multi_key3 | 788.8023 | 736.1453 | 1.0715 |
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/8544 | 2014-10-12T01:56:02Z | 2014-10-13T11:36:39Z | 2014-10-13T11:36:39Z | 2014-10-13T15:32:55Z |
BUG: Plot with ``label`` would overwrite index name | diff --git a/doc/source/whatsnew/v0.15.0.txt b/doc/source/whatsnew/v0.15.0.txt
index 5d7598b749feb..b6b36ce8c1bf9 100644
--- a/doc/source/whatsnew/v0.15.0.txt
+++ b/doc/source/whatsnew/v0.15.0.txt
@@ -1149,4 +1149,3 @@ Bug Fixes
- Suppress FutureWarning generated by NumPy when comparing object arrays containing NaN for equality (:issue:`7065`)
- Bug in ``DataFrame.eval()`` where the dtype of the ``not`` operator (``~``)
was not correctly inferred as ``bool``.
-
diff --git a/doc/source/whatsnew/v0.15.1.txt b/doc/source/whatsnew/v0.15.1.txt
index cd695ab5f992c..1f50470e4cca9 100644
--- a/doc/source/whatsnew/v0.15.1.txt
+++ b/doc/source/whatsnew/v0.15.1.txt
@@ -138,3 +138,8 @@ Bug Fixes
- Fix ``shape`` attribute for ``MultiIndex`` (:issue:`8609`)
- Bug in ``GroupBy`` where a name conflict between the grouper and columns
would break ``groupby`` operations (:issue:`7115`, :issue:`8112`)
+
+
+
+- Fixed a bug where plotting a column ``y`` and specifying a label
+would mutate the index name of the DataFrame ``y`` came from (:issue:`8494`)
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 45814795ec060..a5d203d688b16 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -1058,6 +1058,14 @@ def test_explicit_label(self):
ax = df.plot(x='a', y='b', label='LABEL')
self._check_text_labels(ax.xaxis.get_label(), 'LABEL')
+ @slow
+ def test_donot_overwrite_index_name(self):
+ # GH 8494
+ df = DataFrame(randn(2, 2), columns=['a', 'b'])
+ df.index.name = 'NAME'
+ df.plot(y='b', label='LABEL')
+ self.assertEqual(df.index.name, 'NAME')
+
@slow
def test_plot_xy(self):
# columns.inferred_type == 'string'
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 0e477d8eedb98..9065e0a340aaa 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -2261,7 +2261,8 @@ def _plot(data, x=None, y=None, subplots=False,
elif y is not None:
if com.is_integer(y) and not data.columns.holds_integer():
y = data.columns[y]
- data = data[y] # converted to series actually
+ # converted to series actually. copy to not modify
+ data = data[y].copy()
data.index.name = y
plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
else:
@@ -2276,7 +2277,7 @@ def _plot(data, x=None, y=None, subplots=False,
y = data.columns[y]
label = x if x is not None else data.index.name
label = kwds.pop('label', label)
- series = data[y]
+ series = data[y].copy() # Don't modify
series.index.name = label
for kw in ['xerr', 'yerr']:
| Closes https://github.com/pydata/pandas/issues/8494
I took the easy solution and just copied the series.
Alternatively we could attach a label property to the MPLObject, and check that wherever we check the index name.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8541 | 2014-10-11T19:51:12Z | 2014-10-28T03:56:19Z | 2014-10-28T03:56:19Z | 2017-04-05T02:06:11Z |
BUG: Dont add None to plot legend. | diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 1793d6806be83..38c145cc5f014 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -2477,6 +2477,16 @@ def test_style_by_column(self):
for i, l in enumerate(ax.get_lines()[:len(markers)]):
self.assertEqual(l.get_marker(), markers[i])
+ @slow
+ def test_line_label_none(self):
+ s = Series([1, 2])
+ ax = s.plot()
+ self.assertEqual(ax.get_legend(), None)
+
+ ax = s.plot(legend=True)
+ self.assertEqual(ax.get_legend().get_texts()[0].get_text(),
+ 'None')
+
@slow
def test_line_colors(self):
import sys
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 1d47c3781a7d7..c60cf0986e43e 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -2456,7 +2456,7 @@ def plot_frame(data, x=None, y=None, kind='line', ax=None, # Dat
@Appender(_shared_docs['plot'] % _shared_doc_series_kwargs)
def plot_series(data, kind='line', ax=None, # Series unique
figsize=None, use_index=True, title=None, grid=None,
- legend=True, style=None, logx=False, logy=False, loglog=False,
+ legend=False, style=None, logx=False, logy=False, loglog=False,
xticks=None, yticks=None, xlim=None, ylim=None,
rot=None, fontsize=None, colormap=None, table=False,
yerr=None, xerr=None,
| Closes https://github.com/pydata/pandas/issues/8491
Building the docs now to check that everything looks ok.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8536 | 2014-10-11T12:40:15Z | 2014-10-11T19:27:25Z | 2014-10-11T19:27:25Z | 2017-04-05T02:06:09Z |
DOC: Clean up Sphinx Issues, fix tabs, in Cookbook | diff --git a/doc/source/cookbook.rst b/doc/source/cookbook.rst
index e8c6931cbad34..edff461d7989d 100644
--- a/doc/source/cookbook.rst
+++ b/doc/source/cookbook.rst
@@ -60,7 +60,7 @@ if-then...
**********
An if-then on one column
-
+
.. ipython:: python
df.ix[df.AAA >= 5,'BBB'] = -1; df
@@ -167,7 +167,6 @@ One could hard code:
.. ipython:: python
AllCrit = Crit1 & Crit2 & Crit3
- AllCrit;
...Or it can be done with a list of dynamically built criteria
@@ -467,129 +466,125 @@ Unlike agg, apply's callable is passed a sub-DataFrame which gives you access to
.. ipython:: python
- df = pd.DataFrame({'animal': 'cat dog cat fish dog cat cat'.split(),
- 'size': list('SSMMMLL'),
- 'weight': [8, 10, 11, 1, 20, 12, 12],
- 'adult' : [False] * 5 + [True] * 2}); df
+ df = pd.DataFrame({'animal': 'cat dog cat fish dog cat cat'.split(),
+ 'size': list('SSMMMLL'),
+ 'weight': [8, 10, 11, 1, 20, 12, 12],
+ 'adult' : [False] * 5 + [True] * 2}); df
- #List the size of the animals with the highest weight.
- df.groupby('animal').apply(lambda subf: subf['size'][subf['weight'].idxmax()])
+ #List the size of the animals with the highest weight.
+ df.groupby('animal').apply(lambda subf: subf['size'][subf['weight'].idxmax()])
`Using get_group
<http://stackoverflow.com/questions/14734533/how-to-access-pandas-groupby-dataframe-by-key>`__
.. ipython:: python
- gb = df.groupby(['animal'])
-
- gb.get_group('cat')
-
+ gb = df.groupby(['animal'])
+
+ gb.get_group('cat')
+
`Apply to different items in a group
<http://stackoverflow.com/questions/15262134/apply-different-functions-to-different-items-in-group-object-python-pandas>`__
.. ipython:: python
- def GrowUp(x):
- avg_weight = sum(x[x.size == 'S'].weight * 1.5)
- avg_weight += sum(x[x.size == 'M'].weight * 1.25)
- avg_weight += sum(x[x.size == 'L'].weight)
- avg_weight = avg_weight / len(x)
- return pd.Series(['L',avg_weight,True], index=['size', 'weight', 'adult'])
+ def GrowUp(x):
+ avg_weight = sum(x[x.size == 'S'].weight * 1.5)
+ avg_weight += sum(x[x.size == 'M'].weight * 1.25)
+ avg_weight += sum(x[x.size == 'L'].weight)
+ avg_weight = avg_weight / len(x)
+ return pd.Series(['L',avg_weight,True], index=['size', 'weight', 'adult'])
- expected_df = gb.apply(GrowUp)
-
- expected_df
+ expected_df = gb.apply(GrowUp)
+
+ expected_df
`Expanding Apply
<http://stackoverflow.com/questions/14542145/reductions-down-a-column-in-pandas>`__
.. ipython:: python
- S = pd.Series([i / 100 for i in range(1,11)])
+ S = pd.Series([i / 100.0 for i in range(1,11)])
- def CumRet(x,y):
- return x * (1 + y)
+ def CumRet(x,y):
+ return x * (1 + y)
- def Red(x):
- return functools.reduce(CumRet,x,1.0)
-
- pd.expanding_apply(S, Red)
-
+ def Red(x):
+ return functools.reduce(CumRet,x,1.0)
+
+ pd.expanding_apply(S, Red)
+
+
`Replacing some values with mean of the rest of a group
<http://stackoverflow.com/questions/14760757/replacing-values-with-groupby-means>`__
.. ipython:: python
- df = pd.DataFrame({'A' : [1, 1, 2, 2], 'B' : [1, -1, 1, 2]})
+ df = pd.DataFrame({'A' : [1, 1, 2, 2], 'B' : [1, -1, 1, 2]})
- gb = df.groupby('A')
+ gb = df.groupby('A')
- def replace(g):
- mask = g < 0
- g.loc[mask] = g[~mask].mean()
- return g
+ def replace(g):
+ mask = g < 0
+ g.loc[mask] = g[~mask].mean()
+ return g
- gb.transform(replace)
-
+ gb.transform(replace)
+
`Sort groups by aggregated data
<http://stackoverflow.com/questions/14941366/pandas-sort-by-group-aggregate-and-column>`__
.. ipython:: python
- df = pd.DataFrame({'code': ['foo', 'bar', 'baz'] * 2,
- 'data': [0.16, -0.21, 0.33, 0.45, -0.59, 0.62],
- 'flag': [False, True] * 3})
+ df = pd.DataFrame({'code': ['foo', 'bar', 'baz'] * 2,
+ 'data': [0.16, -0.21, 0.33, 0.45, -0.59, 0.62],
+ 'flag': [False, True] * 3})
- code_groups = df.groupby('code')
+ code_groups = df.groupby('code')
- agg_n_sort_order = code_groups[['data']].transform(sum).sort('data')
+ agg_n_sort_order = code_groups[['data']].transform(sum).sort('data')
- sorted_df = df.ix[agg_n_sort_order.index]
-
- sorted_df
-
+ sorted_df = df.ix[agg_n_sort_order.index]
+
+ sorted_df
+
`Create multiple aggregated columns
<http://stackoverflow.com/questions/14897100/create-multiple-columns-in-pandas-aggregation-function>`__
.. ipython:: python
- rng = pd.date_range(start="2014-10-07",periods=10,freq='2min')
- ts = pd.Series(data = list(range(10)), index = rng)
+ rng = pd.date_range(start="2014-10-07",periods=10,freq='2min')
+ ts = pd.Series(data = list(range(10)), index = rng)
- def MyCust(x):
- if len(x) > 2:
- return x[1] * 1.234
- else:
- return pd.NaT
-
- mhc = {'Mean' : np.mean, 'Max' : np.max, 'Custom' : MyCust}
-
- ts.resample("5min",how = mhc)
-
- ts
-
+ def MyCust(x):
+ if len(x) > 2:
+ return x[1] * 1.234
+ return pd.NaT
+
+ mhc = {'Mean' : np.mean, 'Max' : np.max, 'Custom' : MyCust}
+ ts.resample("5min",how = mhc)
+ ts
+
`Create a value counts column and reassign back to the DataFrame
<http://stackoverflow.com/questions/17709270/i-want-to-create-a-column-of-value-counts-in-my-pandas-dataframe>`__
.. ipython:: python
- df = pd.DataFrame({'Color': 'Red Red Red Blue'.split(),
- 'Value': [100, 150, 50, 50]}); df
-
- df['Counts'] = df.groupby(['Color']).transform(len)
- df
-
+ df = pd.DataFrame({'Color': 'Red Red Red Blue'.split(),
+ 'Value': [100, 150, 50, 50]}); df
+ df['Counts'] = df.groupby(['Color']).transform(len)
+ df
+
`Shift groups of the values in a column based on the index
<http://stackoverflow.com/q/23198053/190597>`__
.. ipython:: python
df = pd.DataFrame(
- {u'line_race': [10, 10, 8, 10, 10, 8],
- u'beyer': [99, 102, 103, 103, 88, 100]},
- index=[u'Last Gunfighter', u'Last Gunfighter', u'Last Gunfighter',
- u'Paynter', u'Paynter', u'Paynter']); df
-
+ {u'line_race': [10, 10, 8, 10, 10, 8],
+ u'beyer': [99, 102, 103, 103, 88, 100]},
+ index=[u'Last Gunfighter', u'Last Gunfighter', u'Last Gunfighter',
+ u'Paynter', u'Paynter', u'Paynter']); df
df['beyer_shifted'] = df.groupby(level=0)['beyer'].shift(1)
df
@@ -615,14 +610,14 @@ Create a list of dataframes, split using a delineation based on logic included i
.. ipython:: python
- df = pd.DataFrame(data={'Case' : ['A','A','A','B','A','A','B','A','A'],
- 'Data' : np.random.randn(9)})
-
- dfs = list(zip(*df.groupby(pd.rolling_median((1*(df['Case']=='B')).cumsum(),3,True))))[-1]
+ df = pd.DataFrame(data={'Case' : ['A','A','A','B','A','A','B','A','A'],
+ 'Data' : np.random.randn(9)})
+
+ dfs = list(zip(*df.groupby(pd.rolling_median((1*(df['Case']=='B')).cumsum(),3,True))))[-1]
- dfs[0]
- dfs[1]
- dfs[2]
+ dfs[0]
+ dfs[1]
+ dfs[2]
.. _cookbook.pivot:
@@ -635,32 +630,32 @@ The :ref:`Pivot <reshaping.pivot>` docs.
.. ipython:: python
- df = pd.DataFrame(data={'Province' : ['ON','QC','BC','AL','AL','MN','ON'],
+ df = pd.DataFrame(data={'Province' : ['ON','QC','BC','AL','AL','MN','ON'],
'City' : ['Toronto','Montreal','Vancouver','Calgary','Edmonton','Winnipeg','Windsor'],
'Sales' : [13,6,16,8,4,3,1]})
- table = pd.pivot_table(df,values=['Sales'],index=['Province'],columns=['City'],aggfunc=np.sum,margins=True)
- table.stack('City')
+ table = pd.pivot_table(df,values=['Sales'],index=['Province'],columns=['City'],aggfunc=np.sum,margins=True)
+ table.stack('City')
`Frequency table like plyr in R
<http://stackoverflow.com/questions/15589354/frequency-tables-in-pandas-like-plyr-in-r>`__
.. ipython:: python
- grades = [48,99,75,80,42,80,72,68,36,78]
- df = pd.DataFrame( {'ID': ["x%d" % r for r in range(10)],
- 'Gender' : ['F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'M'],
- 'ExamYear': ['2007','2007','2007','2008','2008','2008','2008','2009','2009','2009'],
- 'Class': ['algebra', 'stats', 'bio', 'algebra', 'algebra', 'stats', 'stats', 'algebra', 'bio', 'bio'],
- 'Participated': ['yes','yes','yes','yes','no','yes','yes','yes','yes','yes'],
- 'Passed': ['yes' if x > 50 else 'no' for x in grades],
- 'Employed': [True,True,True,False,False,False,False,True,True,False],
- 'Grade': grades})
-
- df.groupby('ExamYear').agg({'Participated': lambda x: x.value_counts()['yes'],
- 'Passed': lambda x: sum(x == 'yes'),
- 'Employed' : lambda x : sum(x),
- 'Grade' : lambda x : sum(x) / len(x)})
-
+ grades = [48,99,75,80,42,80,72,68,36,78]
+ df = pd.DataFrame( {'ID': ["x%d" % r for r in range(10)],
+ 'Gender' : ['F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'M'],
+ 'ExamYear': ['2007','2007','2007','2008','2008','2008','2008','2009','2009','2009'],
+ 'Class': ['algebra', 'stats', 'bio', 'algebra', 'algebra', 'stats', 'stats', 'algebra', 'bio', 'bio'],
+ 'Participated': ['yes','yes','yes','yes','no','yes','yes','yes','yes','yes'],
+ 'Passed': ['yes' if x > 50 else 'no' for x in grades],
+ 'Employed': [True,True,True,False,False,False,False,True,True,False],
+ 'Grade': grades})
+
+ df.groupby('ExamYear').agg({'Participated': lambda x: x.value_counts()['yes'],
+ 'Passed': lambda x: sum(x == 'yes'),
+ 'Employed' : lambda x : sum(x),
+ 'Grade' : lambda x : sum(x) / len(x)})
+
Apply
*****
@@ -669,12 +664,12 @@ Apply
.. ipython:: python
- df = pd.DataFrame(data={'A' : [[2,4,8,16],[100,200],[10,20,30]], 'B' : [['a','b','c'],['jj','kk'],['ccc']]},index=['I','II','III'])
+ df = pd.DataFrame(data={'A' : [[2,4,8,16],[100,200],[10,20,30]], 'B' : [['a','b','c'],['jj','kk'],['ccc']]},index=['I','II','III'])
- def SeriesFromSubList(aList):
- return pd.Series(aList)
+ def SeriesFromSubList(aList):
+ return pd.Series(aList)
- df_orgz = pd.concat(dict([ (ind,row.apply(SeriesFromSubList)) for ind,row in df.iterrows() ]))
+ df_orgz = pd.concat(dict([ (ind,row.apply(SeriesFromSubList)) for ind,row in df.iterrows() ]))
`Rolling Apply with a DataFrame returning a Series
<http://stackoverflow.com/questions/19121854/using-rolling-apply-on-a-dataframe-object>`__
@@ -683,15 +678,15 @@ Rolling Apply to multiple columns where function calculates a Series before a Sc
.. ipython:: python
- df = pd.DataFrame(data=np.random.randn(2000,2)/10000,
- index=pd.date_range('2001-01-01',periods=2000),
- columns=['A','B']); df
+ df = pd.DataFrame(data=np.random.randn(2000,2)/10000,
+ index=pd.date_range('2001-01-01',periods=2000),
+ columns=['A','B']); df
- def gm(aDF,Const):
- v = ((((aDF.A+aDF.B)+1).cumprod())-1)*Const
- return (aDF.index[0],v.iloc[-1])
-
- S = pd.Series(dict([ gm(df.iloc[i:min(i+51,len(df)-1)],5) for i in range(len(df)-50) ])); S
+ def gm(aDF,Const):
+ v = ((((aDF.A+aDF.B)+1).cumprod())-1)*Const
+ return (aDF.index[0],v.iloc[-1])
+
+ S = pd.Series(dict([ gm(df.iloc[i:min(i+51,len(df)-1)],5) for i in range(len(df)-50) ])); S
`Rolling apply with a DataFrame returning a Scalar
<http://stackoverflow.com/questions/21040766/python-pandas-rolling-apply-two-column-input-into-function/21045831#21045831>`__
@@ -700,14 +695,14 @@ Rolling Apply to multiple columns where function returns a Scalar (Volume Weight
.. ipython:: python
- rng = pd.date_range(start = '2014-01-01',periods = 100)
- df = pd.DataFrame({'Open' : np.random.randn(len(rng)),
- 'Close' : np.random.randn(len(rng)),
- 'Volume' : np.random.randint(100,2000,len(rng))}, index=rng); df
+ rng = pd.date_range(start = '2014-01-01',periods = 100)
+ df = pd.DataFrame({'Open' : np.random.randn(len(rng)),
+ 'Close' : np.random.randn(len(rng)),
+ 'Volume' : np.random.randint(100,2000,len(rng))}, index=rng); df
- def vwap(bars): return ((bars.Close*bars.Volume).sum()/bars.Volume.sum()).round(2)
- window = 5
- s = pd.concat([ (pd.Series(vwap(df.iloc[i:i+window]), index=[df.index[i+window]])) for i in range(len(df)-window) ]); s
+ def vwap(bars): return ((bars.Close*bars.Volume).sum()/bars.Volume.sum()).round(2)
+ window = 5
+ s = pd.concat([ (pd.Series(vwap(df.iloc[i:i+window]), index=[df.index[i+window]])) for i in range(len(df)-window) ]); s
Timeseries
----------
@@ -735,8 +730,8 @@ Calculate the first day of the month for each entry in a DatetimeIndex
.. ipython:: python
- dates = pd.date_range('2000-01-01', periods=5)
- dates.to_period(freq='M').to_timestamp()
+ dates = pd.date_range('2000-01-01', periods=5)
+ dates.to_period(freq='M').to_timestamp()
.. _cookbook.resample:
@@ -777,29 +772,29 @@ The :ref:`Concat <merging.concatenation>` docs. The :ref:`Join <merging.join>` d
.. ipython:: python
- rng = pd.date_range('2000-01-01', periods=6)
- df1 = pd.DataFrame(np.random.randn(6, 3), index=rng, columns=['A', 'B', 'C'])
- df2 = df1.copy()
-
+ rng = pd.date_range('2000-01-01', periods=6)
+ df1 = pd.DataFrame(np.random.randn(6, 3), index=rng, columns=['A', 'B', 'C'])
+ df2 = df1.copy()
+
ignore_index is needed in pandas < v0.13, and depending on df construction
.. ipython:: python
- df = df1.append(df2,ignore_index=True); df
+ df = df1.append(df2,ignore_index=True); df
`Self Join of a DataFrame
<https://github.com/pydata/pandas/issues/2996>`__
.. ipython:: python
- df = pd.DataFrame(data={'Area' : ['A'] * 5 + ['C'] * 2,
- 'Bins' : [110] * 2 + [160] * 3 + [40] * 2,
- 'Test_0' : [0, 1, 0, 1, 2, 0, 1],
- 'Data' : np.random.randn(7)});df
-
- df['Test_1'] = df['Test_0'] - 1
+ df = pd.DataFrame(data={'Area' : ['A'] * 5 + ['C'] * 2,
+ 'Bins' : [110] * 2 + [160] * 3 + [40] * 2,
+ 'Test_0' : [0, 1, 0, 1, 2, 0, 1],
+ 'Data' : np.random.randn(7)});df
+
+ df['Test_1'] = df['Test_0'] - 1
- pd.merge(df, df, left_on=['Bins', 'Area','Test_0'], right_on=['Bins', 'Area','Test_1'],suffixes=('_L','_R'))
+ pd.merge(df, df, left_on=['Bins', 'Area','Test_0'], right_on=['Bins', 'Area','Test_1'],suffixes=('_L','_R'))
`How to set the index and join
<http://stackoverflow.com/questions/14341805/pandas-merge-pd-merge-how-to-set-the-index-and-join>`__
@@ -846,19 +841,17 @@ The :ref:`Plotting <visualization>` docs.
.. ipython:: python
- df = pd.DataFrame(
+ df = pd.DataFrame(
{u'stratifying_var': np.random.uniform(0, 100, 20),
- u'price': np.random.normal(100, 5, 20)}
- )
- df[u'quartiles'] = pd.qcut(
- df[u'stratifying_var'],
- 4,
- labels=[u'0-25%', u'25-50%', u'50-75%', u'75-100%']
- )
-
- @savefig quartile_boxplot.png
- df.boxplot(column=u'price', by=u'quartiles')
+ u'price': np.random.normal(100, 5, 20)})
+
+ df[u'quartiles'] = pd.qcut(
+ df[u'stratifying_var'],
+ 4,
+ labels=[u'0-25%', u'25-50%', u'50-75%', u'75-100%'])
+ @savefig quartile_boxplot.png
+ df.boxplot(column=u'price', by=u'quartiles')
Data In/Out
-----------
@@ -1029,19 +1022,19 @@ Storing Attributes to a group node
.. ipython:: python
- df = pd.DataFrame(np.random.randn(8,3))
- store = pd.HDFStore('test.h5')
- store.put('df',df)
-
- # you can store an arbitrary python object via pickle
- store.get_storer('df').attrs.my_attribute = dict(A = 10)
- store.get_storer('df').attrs.my_attribute
+ df = pd.DataFrame(np.random.randn(8,3))
+ store = pd.HDFStore('test.h5')
+ store.put('df',df)
+
+ # you can store an arbitrary python object via pickle
+ store.get_storer('df').attrs.my_attribute = dict(A = 10)
+ store.get_storer('df').attrs.my_attribute
.. ipython:: python
:suppress:
- store.close()
- os.remove('test.h5')
+ store.close()
+ os.remove('test.h5')
.. _cookbook.binary:
@@ -1173,14 +1166,18 @@ To globally provide aliases for axis names, one can define these 2 functions:
.. ipython:: python
def set_axis_alias(cls, axis, alias):
- if axis not in cls._AXIS_NUMBERS:
- raise Exception("invalid axis [%s] for alias [%s]" % (axis, alias))
- cls._AXIS_ALIASES[alias] = axis
+ if axis not in cls._AXIS_NUMBERS:
+ raise Exception("invalid axis [%s] for alias [%s]" % (axis, alias))
+ cls._AXIS_ALIASES[alias] = axis
+
+.. ipython:: python
def clear_axis_alias(cls, axis, alias):
- if axis not in cls._AXIS_NUMBERS:
- raise Exception("invalid axis [%s] for alias [%s]" % (axis, alias))
- cls._AXIS_ALIASES.pop(alias,None)
+ if axis not in cls._AXIS_NUMBERS:
+ raise Exception("invalid axis [%s] for alias [%s]" % (axis, alias))
+ cls._AXIS_ALIASES.pop(alias,None)
+
+.. ipython:: python
set_axis_alias(pd.DataFrame,'columns', 'myaxis2')
df2 = pd.DataFrame(np.random.randn(3,2),columns=['c1','c2'],index=['i1','i2','i3'])
@@ -1197,13 +1194,12 @@ of the data values:
.. ipython:: python
- def expand_grid(data_dict):
- rows = itertools.product(*data_dict.values())
- return pd.DataFrame.from_records(rows, columns=data_dict.keys())
+ def expand_grid(data_dict):
+ rows = itertools.product(*data_dict.values())
+ return pd.DataFrame.from_records(rows, columns=data_dict.keys())
- df = expand_grid(
- {'height': [60, 70],
- 'weight': [100, 140, 180],
- 'sex': ['Male', 'Female']}
- )
- df
\ No newline at end of file
+ df = expand_grid(
+ {'height': [60, 70],
+ 'weight': [100, 140, 180],
+ 'sex': ['Male', 'Female']})
+ df
\ No newline at end of file
| This is a follow on PR as a result of [seeing travis and sphinx render ~30 in line examples for the cookbook](https://github.com/pydata/pandas/pull/8288#issuecomment-58734824).
Continues to address #6918
Initial PR: https://github.com/pydata/pandas/pull/8288
PS - apologies for wanting to rush the first PR. My evening opened up unexpectedly. Feel free to merge this latest, or provide more feedback for me to work on later. I'm going off grid for 2+ days starting oct 10th 11 PM EST.
The latest rendering is [here](https://cloud.githubusercontent.com/assets/6062071/4601203/f3dcdc76-50f0-11e4-8466-4db698bdc3b4.png):
Edit : Removed inline view of humongous rendering, still available for viewing at link above.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8535 | 2014-10-11T02:48:43Z | 2014-10-13T02:19:33Z | 2014-10-13T02:19:33Z | 2015-02-09T00:43:14Z |
Add xray to ecosystem docs | diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst
index e5009aeb1c6f6..c60f9ec9103e5 100644
--- a/doc/source/ecosystem.rst
+++ b/doc/source/ecosystem.rst
@@ -89,3 +89,11 @@ Domain Specific
Geopandas extends pandas data objects to include geographic information which support
geometric operations. If your work entails maps and geographical coordinates, and
you love pandas, you should take a close look at Geopandas.
+
+`xray <https://github.com/xray/xray>`__
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+xray brings the labeled data power of pandas to the physical sciences by
+providing N-dimensional variants of the core pandas data structures. It aims to
+provide a pandas-like and pandas-compatible toolkit for analytics on multi-
+dimensional arrays, rather than the tabular data for which pandas excels.
| Fixes #8516
| https://api.github.com/repos/pandas-dev/pandas/pulls/8534 | 2014-10-10T18:11:45Z | 2014-10-10T22:32:42Z | 2014-10-10T22:32:42Z | 2014-10-10T22:38:00Z |
index into multi-index past the lex-sort depth | diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt
index 944a78ad3691e..6688f106f922e 100644
--- a/doc/source/whatsnew/v0.15.2.txt
+++ b/doc/source/whatsnew/v0.15.2.txt
@@ -19,6 +19,26 @@ users upgrade to this version.
API changes
~~~~~~~~~~~
+- Indexing in ``MultiIndex`` beyond lex-sort depth is now supported, though
+ a lexically sorted index will have a better performance. (:issue:`2646`)
+
+ .. ipython:: python
+
+ df = pd.DataFrame({'jim':[0, 0, 1, 1],
+ 'joe':['x', 'x', 'z', 'y'],
+ 'jolie':np.random.rand(4)}).set_index(['jim', 'joe'])
+ df
+ df.index.lexsort_depth
+
+ # in prior versions this would raise a KeyError
+ # will now show a PerformanceWarning
+ df.loc[(1, 'z')]
+
+ # lexically sorting
+ df2 = df.sortlevel()
+ df2
+ df2.index.lexsort_depth
+ df2.loc[(1,'z')]
- Bug in concat of Series with ``category`` dtype which were coercing to ``object``. (:issue:`8641`)
@@ -129,3 +149,5 @@ Bug Fixes
- Bugs when trying to stack multiple columns, when some (or all)
of the level names are numbers (:issue:`8584`).
+- Bug in ``MultiIndex`` where ``__contains__`` returns wrong result if index is
+ not lexically sorted or unique (:issue:`7724`)
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 3f0b45ae10988..7d9f772126483 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -21,6 +21,7 @@
from pandas.core.common import (_values_from_object, is_float, is_integer,
ABCSeries, _ensure_object, _ensure_int64)
from pandas.core.config import get_option
+from pandas.io.common import PerformanceWarning
# simplify
default_pprint = lambda x: com.pprint_thing(x, escape_chars=('\t', '\r', '\n'),
@@ -4027,7 +4028,9 @@ def _partial_tup_index(self, tup, side='left'):
def get_loc(self, key):
"""
- Get integer location slice for requested label or tuple
+ Get integer location, slice or boolean mask for requested label or tuple
+ If the key is past the lexsort depth, the return may be a boolean mask
+ array, otherwise it is always a slice or int.
Parameters
----------
@@ -4035,22 +4038,73 @@ def get_loc(self, key):
Returns
-------
- loc : int or slice object
- """
- if isinstance(key, tuple):
- if len(key) == self.nlevels:
- if self.is_unique:
- return self._engine.get_loc(_values_from_object(key))
- else:
- return slice(*self.slice_locs(key, key))
- else:
- # partial selection
- result = slice(*self.slice_locs(key, key))
- if result.start == result.stop:
- raise KeyError(key)
- return result
- else:
- return self._get_level_indexer(key, level=0)
+ loc : int, slice object or boolean mask
+ """
+ def _maybe_to_slice(loc):
+ '''convert integer indexer to boolean mask or slice if possible'''
+ if not isinstance(loc, np.ndarray) or loc.dtype != 'int64':
+ return loc
+
+ loc = lib.maybe_indices_to_slice(loc)
+ if isinstance(loc, slice):
+ return loc
+
+ mask = np.empty(len(self), dtype='bool')
+ mask.fill(False)
+ mask[loc] = True
+ return mask
+
+ if not isinstance(key, tuple):
+ loc = self._get_level_indexer(key, level=0)
+ return _maybe_to_slice(loc)
+
+ keylen = len(key)
+ if self.nlevels < keylen:
+ raise KeyError('Key length ({0}) exceeds index depth ({1})'
+ ''.format(keylen, self.nlevels))
+
+ if keylen == self.nlevels and self.is_unique:
+ def _maybe_str_to_time_stamp(key, lev):
+ if lev.is_all_dates and not isinstance(key, Timestamp):
+ try:
+ return Timestamp(key, tz=getattr(lev, 'tz', None))
+ except Exception:
+ pass
+ return key
+ key = _values_from_object(key)
+ key = tuple(map(_maybe_str_to_time_stamp, key, self.levels))
+ return self._engine.get_loc(key)
+
+ # -- partial selection or non-unique index
+ # break the key into 2 parts based on the lexsort_depth of the index;
+ # the first part returns a continuous slice of the index; the 2nd part
+ # needs linear search within the slice
+ i = self.lexsort_depth
+ lead_key, follow_key = key[:i], key[i:]
+ start, stop = self.slice_locs(lead_key, lead_key) \
+ if lead_key else (0, len(self))
+
+ if start == stop:
+ raise KeyError(key)
+
+ if not follow_key:
+ return slice(start, stop)
+
+ warnings.warn('indexing past lexsort depth may impact performance.',
+ PerformanceWarning)
+
+ loc = np.arange(start, stop, dtype='int64')
+
+ for i, k in enumerate(follow_key, len(lead_key)):
+ mask = self.labels[i][loc] == self.levels[i].get_loc(k)
+ if not mask.all():
+ loc = loc[mask]
+ if not len(loc):
+ raise KeyError(key)
+
+ return _maybe_to_slice(loc) \
+ if len(loc) != stop - start \
+ else slice(start, stop)
def get_loc_level(self, key, level=0, drop_level=True):
"""
@@ -4115,10 +4169,10 @@ def _maybe_drop_levels(indexer, levels, drop_level):
if not any(isinstance(k, slice) for k in key):
# partial selection
- def partial_selection(key):
- indexer = slice(*self.slice_locs(key, key))
- if indexer.start == indexer.stop:
- raise KeyError(key)
+ # optionally get indexer to avoid re-calculation
+ def partial_selection(key, indexer=None):
+ if indexer is None:
+ indexer = self.get_loc(key)
ilevels = [i for i in range(len(key))
if key[i] != slice(None, None)]
return indexer, _maybe_drop_levels(indexer, ilevels,
@@ -4139,11 +4193,12 @@ def partial_selection(key):
if any([
l.is_all_dates for k, l in zip(key, self.levels)
]) and not can_index_exactly:
- indexer = slice(*self.slice_locs(key, key))
+ indexer = self.get_loc(key)
# we have a multiple selection here
- if not indexer.stop - indexer.start == 1:
- return partial_selection(key)
+ if not isinstance(indexer, slice) \
+ or indexer.stop - indexer.start != 1:
+ return partial_selection(key, indexer)
key = tuple(self[indexer].tolist()[0])
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 14c4fb17c2b34..ef33e27d861fd 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -3257,7 +3257,9 @@ def take(self, indexer, axis=1, verify=True, convert=True):
Take items along any axis.
"""
self._consolidate_inplace()
- indexer = np.asanyarray(indexer, dtype=np.int_)
+ indexer = np.arange(indexer.start, indexer.stop, indexer.step,
+ dtype='int64') if isinstance(indexer, slice) \
+ else np.asanyarray(indexer, dtype='int64')
n = self.shape[axis]
if convert:
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 76be2e64de8d0..e710ef5ed0a41 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1488,6 +1488,86 @@ def test_loc_multiindex(self):
result = s.loc[2:4:2, 'a':'c']
assert_series_equal(result, expected)
+ def test_multiindex_perf_warn(self):
+ import sys
+ from pandas.io.common import PerformanceWarning
+
+ if sys.version_info < (2, 7):
+ raise nose.SkipTest('python version < 2.7')
+
+ df = DataFrame({'jim':[0, 0, 1, 1],
+ 'joe':['x', 'x', 'z', 'y'],
+ 'jolie':np.random.rand(4)}).set_index(['jim', 'joe'])
+
+ with tm.assert_produces_warning(PerformanceWarning):
+ _ = df.loc[(1, 'z')]
+
+ df = df.iloc[[2,1,3,0]]
+ with tm.assert_produces_warning(PerformanceWarning):
+ _ = df.loc[(0,)]
+
+ def test_multiindex_get_loc(self): # GH7724, GH2646
+ # test indexing into a multi-index before & past the lexsort depth
+ from numpy.random import randint, choice, randn
+ cols = ['jim', 'joe', 'jolie', 'joline', 'jolia']
+
+ def validate(mi, df, key):
+ mask = np.ones(len(df)).astype('bool')
+
+ # test for all partials of this key
+ for i, k in enumerate(key):
+ mask &= df.iloc[:, i] == k
+
+ if not mask.any():
+ self.assertNotIn(key[:i+1], mi.index)
+ continue
+
+ self.assertIn(key[:i+1], mi.index)
+ right = df[mask].copy()
+
+ if i + 1 != len(key): # partial key
+ right.drop(cols[:i+1], axis=1, inplace=True)
+ right.set_index(cols[i+1:-1], inplace=True)
+ assert_frame_equal(mi.loc[key[:i+1]], right)
+
+ else: # full key
+ right.set_index(cols[:-1], inplace=True)
+ if len(right) == 1: # single hit
+ right = Series(right['jolia'].values,
+ name=right.index[0], index=['jolia'])
+ assert_series_equal(mi.loc[key[:i+1]], right)
+ else: # multi hit
+ assert_frame_equal(mi.loc[key[:i+1]], right)
+
+ def loop(mi, df, keys):
+ for key in keys:
+ validate(mi, df, key)
+
+ n, m = 1000, 50
+
+ vals = [randint(0, 10, n), choice(list('abcdefghij'), n),
+ choice(pd.date_range('20141009', periods=10).tolist(), n),
+ choice(list('ZYXWVUTSRQ'), n), randn(n)]
+ vals = list(map(tuple, zip(*vals)))
+
+ # bunch of keys for testing
+ keys = [randint(0, 11, m), choice(list('abcdefghijk'), m),
+ choice(pd.date_range('20141009', periods=11).tolist(), m),
+ choice(list('ZYXWVUTSRQP'), m)]
+ keys = list(map(tuple, zip(*keys)))
+ keys += list(map(lambda t: t[:-1], vals[::n//m]))
+
+ # covers both unique index and non-unique index
+ df = pd.DataFrame(vals, columns=cols)
+ a, b = pd.concat([df, df]), df.drop_duplicates(subset=cols[:-1])
+
+ for frame in a, b:
+ for i in range(5): # lexsort depth
+ df = frame.copy() if i == 0 else frame.sort(columns=cols[:i])
+ mi = df.set_index(cols[:-1])
+ assert not mi.index.lexsort_depth < i
+ loop(mi, df, keys)
+
def test_series_getitem_multiindex(self):
# GH 6018
@@ -1541,10 +1621,7 @@ def test_ix_general(self):
'year': {0: 2012, 1: 2011, 2: 2012, 3: 2012, 4: 2012}}
df = DataFrame(data).set_index(keys=['col', 'year'])
key = 4.0, 2012
-
- # this should raise correct error
- with tm.assertRaises(KeyError):
- df.ix[key]
+ tm.assert_frame_equal(df.ix[key], df.iloc[2:])
# this is ok
df.sortlevel(inplace=True)
| closes https://github.com/pydata/pandas/issues/7724
closes https://github.com/pydata/pandas/issues/2646
on current master:
```
>>> df
jolia
jim joe jolie joline
1 z 2014-10-14 a 30
y 2014-10-13 b 3
x 2014-10-12 c 15
0 z 2014-10-11 d 35
y 2014-10-10 e 43
x 2014-10-09 f 36
```
False negative if the key length exceeds lexsort depth:
```
>>> (0,) in df.index
False
>>> (0, 'z') in df.index
False
>>> (0, 'z', '2014-10-11') in df.index
False
>>> (0, 'z', Timestamp('2014-10-11')) in df.index
False
>>> (0, 'z', '2014-10-11', 'd') in df.index
False
```
only ones which work:
```
>>> 0 in df.index
True
>>> (0, 'z', Timestamp('2014-10-11'), 'd') in df.index
True
```
which take a different code paths. The last one only works if the index is unique:
```
>>> (0, 'z', Timestamp('2014-10-11'), 'd') in pd.concat([df, df]).index
False
```
for all of the false negative cases above, obviously `df.loc[key]` fails:
```
>>> df.loc[(0, 'z', Timestamp('2014-10-11'))]
KeyError: 'Key length (3) was greater than MultiIndex lexsort depth (0)'
```
_Some of these issues persist even if the index is lexically sorted:_
```
>>> df.sort_index(inplace=True)
>>> df # lexically sorted
jolia
jim joe jolie joline
0 x 2014-10-09 f 36
y 2014-10-10 e 43
z 2014-10-11 d 35
1 x 2014-10-12 c 15
y 2014-10-13 b 3
z 2014-10-14 a 30
```
date-time indexing with a full-key fails if index is unique:
```
>>> (0, 'x', '2014-10-09') in df.index # partial key, works!
True
>>> (0, 'x', '2014-10-09', 'f') in df.index # full key, unique index, breaks!
False
```
also, non-unique lexically sorted index always returns false positive with any full key:
```
>>> xdf = pd.concat([df, df]).sort_index()
>>> xdf
jolia
jim joe jolie joline
0 x 2014-10-09 f 36
f 36
y 2014-10-10 e 43
e 43
z 2014-10-11 d 35
d 35
1 x 2014-10-12 c 15
c 15
y 2014-10-13 b 3
b 3
z 2014-10-14 a 30
a 30
>>> (0, '$', '2014-10-09') in xdf.index # partial key works
False
>>> (0, '$', '2014-10-09', '#') in xdf.index # full key always `True`
True
>>> xdf.loc[(0, '$', '2014-10-09', '#')]
KeyError: 'the label [$] is not in the [columns]'
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/8526 | 2014-10-10T02:56:48Z | 2014-11-21T23:20:24Z | 2014-11-21T23:20:24Z | 2014-11-22T14:47:11Z |
BUG/REGR: bool-like Indexes not properly coercing to object (GH8522) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index eec424f619bde..d972edeb2bbb3 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -642,7 +642,7 @@ Internal Refactoring
In 0.15.0 ``Index`` has internally been refactored to no longer sub-class ``ndarray``
but instead subclass ``PandasObject``, similarly to the rest of the pandas objects. This change allows very easy sub-classing and creation of new index types. This should be
-a transparent change with only very limited API implications (:issue:`5080`, :issue:`7439`, :issue:`7796`, :issue:`8024`, :issue:`8367`, :issue:`7997`)
+a transparent change with only very limited API implications (:issue:`5080`, :issue:`7439`, :issue:`7796`, :issue:`8024`, :issue:`8367`, :issue:`7997`, :issue:`8522`)
- you may need to unpickle pandas version < 0.15.0 pickles using ``pd.read_pickle`` rather than ``pickle.load``. See :ref:`pickle docs <io.pickle>`
- when plotting with a ``PeriodIndex``. The ``matplotlib`` internal axes will now be arrays of ``Period`` rather than a ``PeriodIndex``. (this is similar to how a ``DatetimeIndex`` passes arrays of ``datetimes`` now)
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 794c05db082c7..5d6f39e1792c3 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -499,7 +499,7 @@ def searchsorted(self, key, side='left'):
@Appender(_shared_docs['drop_duplicates'] % _indexops_doc_kwargs)
def drop_duplicates(self, take_last=False, inplace=False):
duplicated = self.duplicated(take_last=take_last)
- result = self[~duplicated.values]
+ result = self[~(duplicated.values).astype(bool)]
if inplace:
return self._update_inplace(result)
else:
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 99f1682b133c3..f87b7e982b332 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -148,16 +148,16 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False,
data = np.array(data, dtype=dtype, copy=copy)
except TypeError:
pass
- elif isinstance(data, PeriodIndex):
- return PeriodIndex(data, copy=copy, name=name, **kwargs)
+ # maybe coerce to a sub-class
+ if isinstance(data, PeriodIndex):
+ return PeriodIndex(data, copy=copy, name=name, **kwargs)
if issubclass(data.dtype.type, np.integer):
return Int64Index(data, copy=copy, dtype=dtype, name=name)
- if issubclass(data.dtype.type, np.floating):
+ elif issubclass(data.dtype.type, np.floating):
return Float64Index(data, copy=copy, dtype=dtype, name=name)
-
- if com.is_bool_dtype(data):
- subarr = data
+ elif issubclass(data.dtype.type, np.bool) or com.is_bool_dtype(data):
+ subarr = data.astype('object')
else:
subarr = com._asarray_tuplesafe(data, dtype=object)
@@ -583,6 +583,9 @@ def is_unique(self):
""" return if the index has unique values """
return self._engine.is_unique
+ def is_boolean(self):
+ return self.inferred_type in ['boolean']
+
def is_integer(self):
return self.inferred_type in ['integer']
@@ -592,6 +595,9 @@ def is_floating(self):
def is_numeric(self):
return self.inferred_type in ['integer', 'floating']
+ def is_object(self):
+ return self.dtype == np.object_
+
def is_mixed(self):
return 'mixed' in self.inferred_type
diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py
index f508b8915da1c..814da043d0319 100644
--- a/pandas/tests/test_base.py
+++ b/pandas/tests/test_base.py
@@ -180,6 +180,7 @@ def f():
class Ops(tm.TestCase):
def setUp(self):
+ self.bool_index = tm.makeBoolIndex(10)
self.int_index = tm.makeIntIndex(10)
self.float_index = tm.makeFloatIndex(10)
self.dt_index = tm.makeDateIndex(10)
@@ -189,14 +190,15 @@ def setUp(self):
arr = np.random.randn(10)
self.int_series = Series(arr, index=self.int_index)
- self.float_series = Series(arr, index=self.int_index)
+ self.float_series = Series(arr, index=self.float_index)
self.dt_series = Series(arr, index=self.dt_index)
self.dt_tz_series = self.dt_tz_index.to_series(keep_tz=True)
self.period_series = Series(arr, index=self.period_index)
self.string_series = Series(arr, index=self.string_index)
- types = ['int','float','dt', 'dt_tz', 'period','string']
- self.objs = [ getattr(self,"{0}_{1}".format(t,f)) for t in types for f in ['index','series'] ]
+ types = ['bool','int','float','dt', 'dt_tz', 'period','string']
+ fmts = [ "{0}_{1}".format(t,f) for t in types for f in ['index','series'] ]
+ self.objs = [ getattr(self,f) for f in fmts if getattr(self,f,None) is not None ]
def check_ops_properties(self, props, filter=None, ignore_failures=False):
for op in props:
@@ -340,6 +342,9 @@ def test_value_counts_unique_nunique(self):
# freq must be specified because repeat makes freq ambiguous
expected_index = o[::-1]
o = klass(np.repeat(values, range(1, len(o) + 1)), freq=o.freq)
+ # don't test boolean
+ elif isinstance(o,Index) and o.is_boolean():
+ continue
elif isinstance(o, Index):
expected_index = values[::-1]
o = klass(np.repeat(values, range(1, len(o) + 1)))
@@ -366,6 +371,10 @@ def test_value_counts_unique_nunique(self):
klass = type(o)
values = o.values
+ if isinstance(o,Index) and o.is_boolean():
+ # don't test boolean
+ continue
+
if ((isinstance(o, Int64Index) and not isinstance(o,
(DatetimeIndex, PeriodIndex)))):
# skips int64 because it doesn't allow to include nan or None
@@ -537,7 +546,14 @@ def test_value_counts_inferred(self):
def test_factorize(self):
for o in self.objs:
- exp_arr = np.array(range(len(o)))
+
+ if isinstance(o,Index) and o.is_boolean():
+ exp_arr = np.array([0,1] + [0] * 8)
+ exp_uniques = o
+ exp_uniques = Index([False,True])
+ else:
+ exp_arr = np.array(range(len(o)))
+ exp_uniques = o
labels, uniques = o.factorize()
self.assert_numpy_array_equal(labels, exp_arr)
@@ -545,16 +561,22 @@ def test_factorize(self):
expected = Index(o.values)
self.assert_numpy_array_equal(uniques, expected)
else:
- self.assertTrue(uniques.equals(o))
+ self.assertTrue(uniques.equals(exp_uniques))
for o in self.objs:
+
+ # don't test boolean
+ if isinstance(o,Index) and o.is_boolean():
+ continue
+
# sort by value, and create duplicates
if isinstance(o, Series):
o.sort()
+ n = o.iloc[5:].append(o)
else:
indexer = o.argsort()
o = o.take(indexer)
- n = o[5:].append(o)
+ n = o[5:].append(o)
exp_arr = np.array([5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
labels, uniques = n.factorize(sort=True)
@@ -582,6 +604,14 @@ def test_duplicated_drop_duplicates(self):
for original in self.objs:
if isinstance(original, Index):
+
+ # special case
+ if original.is_boolean():
+ result = original.drop_duplicates()
+ expected = Index([False,True])
+ tm.assert_index_equal(result, expected)
+ continue
+
# original doesn't have duplicates
expected = Index([False] * len(original))
tm.assert_index_equal(original.duplicated(), expected)
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 9984ad30612db..a8c4548f462ac 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -94,6 +94,7 @@ def setUp(self):
dateIndex = tm.makeDateIndex(100),
intIndex = tm.makeIntIndex(100),
floatIndex = tm.makeFloatIndex(100),
+ boolIndex = Index([True,False]),
empty = Index([]),
tuples = MultiIndex.from_tuples(lzip(['foo', 'bar', 'baz'],
[1, 2, 3]))
@@ -732,6 +733,13 @@ def test_is_numeric(self):
self.assertTrue(self.intIndex.is_numeric())
self.assertTrue(self.floatIndex.is_numeric())
+ def test_is_object(self):
+ self.assertTrue(self.strIndex.is_object())
+ self.assertTrue(self.boolIndex.is_object())
+ self.assertFalse(self.intIndex.is_object())
+ self.assertFalse(self.dateIndex.is_object())
+ self.assertFalse(self.floatIndex.is_object())
+
def test_is_all_dates(self):
self.assertTrue(self.dateIndex.is_all_dates)
self.assertFalse(self.strIndex.is_all_dates)
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index d3f7414289053..29bdb2c983d61 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -1222,7 +1222,7 @@ def test_getitem_dups(self):
expected = Series([3,4],index=['C','C'],dtype=np.int64)
result = s['C']
assert_series_equal(result, expected)
-
+
def test_getitem_dataframe(self):
rng = list(range(10))
s = pd.Series(10, index=rng)
@@ -1817,6 +1817,13 @@ def test_drop(self):
# bad axis
self.assertRaises(ValueError, s.drop, 'one', axis='columns')
+ # GH 8522
+ s = Series([2,3], index=[True, False])
+ self.assertTrue(s.index.is_object())
+ result = s.drop(True)
+ expected = Series([3],index=[False])
+ assert_series_equal(result,expected)
+
def test_ix_setitem(self):
inds = self.series.index[[3, 4, 7]]
diff --git a/pandas/util/testing.py b/pandas/util/testing.py
index 977d445f917a8..d8cc39908a31f 100644
--- a/pandas/util/testing.py
+++ b/pandas/util/testing.py
@@ -738,6 +738,13 @@ def makeStringIndex(k=10):
def makeUnicodeIndex(k=10):
return Index([randu(10) for _ in range(k)])
+def makeBoolIndex(k=10):
+ if k == 1:
+ return Index([True])
+ elif k == 2:
+ return Index([False,True])
+ return Index([False,True] + [False]*(k-2))
+
def makeIntIndex(k=10):
return Index(lrange(k))
| closes #8522
| https://api.github.com/repos/pandas-dev/pandas/pulls/8523 | 2014-10-09T17:11:37Z | 2014-10-09T18:32:16Z | 2014-10-09T18:32:16Z | 2014-10-09T18:32:16Z |
BUG: Bug in inplace operations with column sub-selections on the lhs (GH8511) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index e76a0e57c5e33..eec424f619bde 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -272,6 +272,46 @@ API changes
df
df.dtypes
+- In prior versions, updating a pandas object inplace would not reflect in other python references to this object. (:issue:`8511`,:issue:`5104`)
+
+ .. ipython:: python
+
+ s = Series([1, 2, 3])
+ s2 = s
+ s += 1.5
+
+ Behavior prior to v0.15.0
+
+ .. code-block:: python
+
+
+ # the original object
+ In [5]: s
+ Out[5]:
+ 0 2.5
+ 1 3.5
+ 2 4.5
+ dtype: float64
+
+
+ # a reference to the original object
+ In [7]: s2
+ Out[7]:
+ 0 1
+ 1 2
+ 2 3
+ dtype: int64
+
+ This is now the correct behavior
+
+ .. ipython:: python
+
+ # the original object
+ s
+
+ # a reference to the original object
+ s2
+
- ``Series.to_csv()`` now returns a string when ``path=None``, matching the behaviour of ``DataFrame.to_csv()`` (:issue:`8215`).
- ``read_hdf`` now raises ``IOError`` when a file that doesn't exist is passed in. Previously, a new, empty file was created, and a ``KeyError`` raised (:issue:`7715`).
@@ -954,7 +994,6 @@ Bug Fixes
- Bug in ``DataFrame.reset_index`` which has ``MultiIndex`` contains ``PeriodIndex`` or ``DatetimeIndex`` with tz raises ``ValueError`` (:issue:`7746`, :issue:`7793`)
-
- Bug in ``DataFrame.plot`` with ``subplots=True`` may draw unnecessary minor xticks and yticks (:issue:`7801`)
- Bug in ``StataReader`` which did not read variable labels in 117 files due to difference between Stata documentation and implementation (:issue:`7816`)
- Bug in ``StataReader`` where strings were always converted to 244 characters-fixed width irrespective of underlying string size (:issue:`7858`)
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 36cf3d9c7407c..794c05db082c7 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -538,6 +538,6 @@ def duplicated(self, take_last=False):
#----------------------------------------------------------------------
# abstracts
- def _update_inplace(self, result):
+ def _update_inplace(self, result, **kwargs):
raise NotImplementedError
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 7d3716a8a2fa6..53abfe10fe8ea 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1108,9 +1108,21 @@ def _is_view(self):
""" boolean : return if I am a view of another array """
return self._data.is_view
- def _maybe_update_cacher(self, clear=False):
- """ see if we need to update our parent cacher
- if clear, then clear our cache """
+ def _maybe_update_cacher(self, clear=False, verify_is_copy=True):
+ """
+
+ see if we need to update our parent cacher
+ if clear, then clear our cache
+
+ Parameters
+ ----------
+ clear : boolean, default False
+ clear the item cache
+ verify_is_copy : boolean, default True
+ provide is_copy checks
+
+ """
+
cacher = getattr(self, '_cacher', None)
if cacher is not None:
ref = cacher[1]()
@@ -1125,8 +1137,8 @@ def _maybe_update_cacher(self, clear=False):
except:
pass
- # check if we are a copy
- self._check_setitem_copy(stacklevel=5, t='referant')
+ if verify_is_copy:
+ self._check_setitem_copy(stacklevel=5, t='referant')
if clear:
self._clear_item_cache()
@@ -1564,14 +1576,23 @@ def drop(self, labels, axis=0, level=None, inplace=False, **kwargs):
else:
return result
- def _update_inplace(self, result):
- "replace self internals with result."
+ def _update_inplace(self, result, verify_is_copy=True):
+ """
+ replace self internals with result.
+
+ Parameters
+ ----------
+ verify_is_copy : boolean, default True
+ provide is_copy checks
+
+ """
# NOTE: This does *not* call __finalize__ and that's an explicit
# decision that we may revisit in the future.
+
self._reset_cache()
self._clear_item_cache()
self._data = getattr(result,'_data',result)
- self._maybe_update_cacher()
+ self._maybe_update_cacher(verify_is_copy=verify_is_copy)
def add_prefix(self, prefix):
"""
diff --git a/pandas/core/index.py b/pandas/core/index.py
index e10f4b2009817..99f1682b133c3 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -220,7 +220,7 @@ def _simple_new(cls, values, name=None, **kwargs):
result._reset_identity()
return result
- def _update_inplace(self, result):
+ def _update_inplace(self, result, **kwargs):
# guard when called from IndexOpsMixin
raise TypeError("Index can't be updated inplace")
diff --git a/pandas/core/ops.py b/pandas/core/ops.py
index 2c7d92afe3b79..068cdff7fcf2d 100644
--- a/pandas/core/ops.py
+++ b/pandas/core/ops.py
@@ -161,20 +161,39 @@ def add_special_arithmetic_methods(cls, arith_method=None, radd_func=None,
if passed, will not set functions with names in exclude
"""
radd_func = radd_func or operator.add
+
# in frame, special methods have default_axis = None, comp methods use
# 'columns'
+
new_methods = _create_methods(arith_method, radd_func, comp_method,
bool_method, use_numexpr, default_axis=None,
special=True)
# inplace operators (I feel like these should get passed an `inplace=True`
# or just be removed
+
+ def _wrap_inplace_method(method):
+ """
+ return an inplace wrapper for this method
+ """
+
+ def f(self, other):
+ result = method(self, other)
+
+ # this makes sure that we are aligned like the input
+ # we are updating inplace so we want to ignore is_copy
+ self._update_inplace(result.reindex_like(self,copy=False)._data,
+ verify_is_copy=False)
+
+ return self
+ return f
+
new_methods.update(dict(
- __iadd__=new_methods["__add__"],
- __isub__=new_methods["__sub__"],
- __imul__=new_methods["__mul__"],
- __itruediv__=new_methods["__truediv__"],
- __ipow__=new_methods["__pow__"]
+ __iadd__=_wrap_inplace_method(new_methods["__add__"]),
+ __isub__=_wrap_inplace_method(new_methods["__sub__"]),
+ __imul__=_wrap_inplace_method(new_methods["__mul__"]),
+ __itruediv__=_wrap_inplace_method(new_methods["__truediv__"]),
+ __ipow__=_wrap_inplace_method(new_methods["__pow__"]),
))
if not compat.PY3:
new_methods["__idiv__"] = new_methods["__div__"]
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 95a7b22b90338..0408d62ce302c 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -267,8 +267,9 @@ def _set_subtyp(self, is_all_dates):
else:
object.__setattr__(self, '_subtyp', 'series')
- def _update_inplace(self, result):
- return generic.NDFrame._update_inplace(self, result)
+ def _update_inplace(self, result, **kwargs):
+ # we want to call the generic version and not the IndexOpsMixin
+ return generic.NDFrame._update_inplace(self, result, **kwargs)
# ndarray compatibility
@property
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index ba81d98510f5c..3efd399450d11 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -249,6 +249,109 @@ def test_setitem_mulit_index(self):
df[('joe', 'last')] = df[('jolie', 'first')].loc[i, j]
assert_frame_equal(df[('joe', 'last')], df[('jolie', 'first')])
+ def test_inplace_ops_alignment(self):
+
+ # inplace ops / ops alignment
+ # GH 8511
+
+ columns = list('abcdefg')
+ X_orig = DataFrame(np.arange(10*len(columns)).reshape(-1,len(columns)), columns=columns, index=range(10))
+ Z = 100*X_orig.iloc[:,1:-1].copy()
+ block1 = list('bedcf')
+ subs = list('bcdef')
+
+ # add
+ X = X_orig.copy()
+ result1 = (X[block1] + Z).reindex(columns=subs)
+
+ X[block1] += Z
+ result2 = X.reindex(columns=subs)
+
+ X = X_orig.copy()
+ result3 = (X[block1] + Z[block1]).reindex(columns=subs)
+
+ X[block1] += Z[block1]
+ result4 = X.reindex(columns=subs)
+
+ assert_frame_equal(result1, result2)
+ assert_frame_equal(result1, result3)
+ assert_frame_equal(result1, result4)
+
+ # sub
+ X = X_orig.copy()
+ result1 = (X[block1] - Z).reindex(columns=subs)
+
+ X[block1] -= Z
+ result2 = X.reindex(columns=subs)
+
+ X = X_orig.copy()
+ result3 = (X[block1] - Z[block1]).reindex(columns=subs)
+
+ X[block1] -= Z[block1]
+ result4 = X.reindex(columns=subs)
+
+ assert_frame_equal(result1, result2)
+ assert_frame_equal(result1, result3)
+ assert_frame_equal(result1, result4)
+
+ def test_inplace_ops_identity(self):
+
+ # GH 5104
+ # make sure that we are actually changing the object
+ s_orig = Series([1, 2, 3])
+ df_orig = DataFrame(np.random.randint(0,5,size=10).reshape(-1,5))
+
+ # no dtype change
+ s = s_orig.copy()
+ s2 = s
+ s += 1
+ assert_series_equal(s,s2)
+ assert_series_equal(s_orig+1,s)
+ self.assertIs(s,s2)
+ self.assertIs(s._data,s2._data)
+
+ df = df_orig.copy()
+ df2 = df
+ df += 1
+ assert_frame_equal(df,df2)
+ assert_frame_equal(df_orig+1,df)
+ self.assertIs(df,df2)
+ self.assertIs(df._data,df2._data)
+
+ # dtype change
+ s = s_orig.copy()
+ s2 = s
+ s += 1.5
+ assert_series_equal(s,s2)
+ assert_series_equal(s_orig+1.5,s)
+
+ df = df_orig.copy()
+ df2 = df
+ df += 1.5
+ assert_frame_equal(df,df2)
+ assert_frame_equal(df_orig+1.5,df)
+ self.assertIs(df,df2)
+ self.assertIs(df._data,df2._data)
+
+ # mixed dtype
+ arr = np.random.randint(0,10,size=5)
+ df_orig = DataFrame({'A' : arr.copy(), 'B' : 'foo'})
+ df = df_orig.copy()
+ df2 = df
+ df['A'] += 1
+ expected = DataFrame({'A' : arr.copy()+1, 'B' : 'foo'})
+ assert_frame_equal(df,expected)
+ assert_frame_equal(df2,expected)
+ self.assertIs(df._data,df2._data)
+
+ df = df_orig.copy()
+ df2 = df
+ df['A'] += 1.5
+ expected = DataFrame({'A' : arr.copy()+1.5, 'B' : 'foo'})
+ assert_frame_equal(df,expected)
+ assert_frame_equal(df2,expected)
+ self.assertIs(df._data,df2._data)
+
def test_getitem_boolean(self):
# boolean indexing
d = self.tsframe.index[10]
@@ -4979,7 +5082,6 @@ def test_div(self):
self.assertFalse(np.array_equal(res.fillna(0), res2.fillna(0)))
def test_logical_operators(self):
- import operator
def _check_bin_op(op):
result = op(df1, df2)
| closes #8511
closes #5104
| https://api.github.com/repos/pandas-dev/pandas/pulls/8520 | 2014-10-09T12:06:03Z | 2014-10-09T13:36:59Z | 2014-10-09T13:36:59Z | 2014-10-09T13:36:59Z |
BUG: fix CategoricalBlock pickling | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index af47ee878b1c3..ee573da00abdb 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -656,7 +656,7 @@ Categoricals in Series/DataFrame
:class:`~pandas.Categorical` can now be included in `Series` and `DataFrames` and gained new
methods to manipulate. Thanks to Jan Schulz for much of this API/implementation. (:issue:`3943`, :issue:`5313`, :issue:`5314`,
:issue:`7444`, :issue:`7839`, :issue:`7848`, :issue:`7864`, :issue:`7914`, :issue:`7768`, :issue:`8006`, :issue:`3678`,
-:issue:`8075`, :issue:`8076`, :issue:`8143`, :issue:`8453`).
+:issue:`8075`, :issue:`8076`, :issue:`8143`, :issue:`8453`, :issue:`8518`).
For full docs, see the :ref:`categorical introduction <categorical>` and the
:ref:`API documentation <api.categorical>`.
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index aa5fa29784912..b35cfdcf7c8f1 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -187,6 +187,8 @@ class Categorical(PandasObject):
# For comparisons, so that numpy uses our implementation if the compare ops, which raise
__array_priority__ = 1000
+ ordered = False
+ name = None
def __init__(self, values, categories=None, ordered=None, name=None, fastpath=False,
levels=None):
@@ -718,6 +720,21 @@ def __array__(self, dtype=None):
return np.asarray(ret, dtype)
return ret
+ def __setstate__(self, state):
+ """Necessary for making this object picklable"""
+ if not isinstance(state, dict):
+ raise Exception('invalid pickle state')
+
+ # Provide compatibility with pre-0.15.0 Categoricals.
+ if '_codes' not in state and 'labels' in state:
+ state['_codes'] = state.pop('labels')
+ if '_categories' not in state and '_levels' in state:
+ state['_categories'] = \
+ self._validate_categories(state.pop('_levels'))
+
+ for k, v in compat.iteritems(state):
+ setattr(self, k, v)
+
@property
def T(self):
return self
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index c88d799a54fed..9be680d998216 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1070,16 +1070,19 @@ class NonConsolidatableMixIn(object):
def __init__(self, values, placement,
ndim=None, fastpath=False,):
+ # Placement must be converted to BlockPlacement via property setter
+ # before ndim logic, because placement may be a slice which doesn't
+ # have a length.
+ self.mgr_locs = placement
+
# kludgetastic
if ndim is None:
- if len(placement) != 1:
+ if len(self.mgr_locs) != 1:
ndim = 1
else:
ndim = 2
self.ndim = ndim
- self.mgr_locs = placement
-
if not isinstance(values, self._holder):
raise TypeError("values must be {0}".format(self._holder.__name__))
@@ -1852,6 +1855,7 @@ def get_values(self, dtype=None):
.reshape(self.values.shape)
return self.values
+
class SparseBlock(NonConsolidatableMixIn, Block):
""" implement as a list of sparse arrays of the same dtype """
__slots__ = ()
@@ -1861,27 +1865,6 @@ class SparseBlock(NonConsolidatableMixIn, Block):
_ftype = 'sparse'
_holder = SparseArray
- def __init__(self, values, placement,
- ndim=None, fastpath=False,):
-
- # Placement must be converted to BlockPlacement via property setter
- # before ndim logic, because placement may be a slice which doesn't
- # have a length.
- self.mgr_locs = placement
-
- # kludgetastic
- if ndim is None:
- if len(self.mgr_locs) != 1:
- ndim = 1
- else:
- ndim = 2
- self.ndim = ndim
-
- if not isinstance(values, SparseArray):
- raise TypeError("values must be SparseArray")
-
- self.values = values
-
@property
def shape(self):
return (len(self.mgr_locs), self.sp_index.length)
diff --git a/pandas/io/tests/data/legacy_pickle/0.15.0/0.15.0_x86_64_linux_2.7.8.pickle b/pandas/io/tests/data/legacy_pickle/0.15.0/0.15.0_x86_64_linux_2.7.8.pickle
new file mode 100644
index 0000000000000..d7d20b06df305
Binary files /dev/null and b/pandas/io/tests/data/legacy_pickle/0.15.0/0.15.0_x86_64_linux_2.7.8.pickle differ
diff --git a/pandas/io/tests/generate_legacy_pickles.py b/pandas/io/tests/generate_legacy_pickles.py
index b20a1e5b60b86..56ef1aa9b0f19 100644
--- a/pandas/io/tests/generate_legacy_pickles.py
+++ b/pandas/io/tests/generate_legacy_pickles.py
@@ -60,7 +60,7 @@ def create_data():
from pandas import (Series,TimeSeries,DataFrame,Panel,
SparseSeries,SparseTimeSeries,SparseDataFrame,SparsePanel,
Index,MultiIndex,PeriodIndex,
- date_range,period_range,bdate_range,Timestamp)
+ date_range,period_range,bdate_range,Timestamp,Categorical)
nan = np.nan
data = {
@@ -85,7 +85,8 @@ def create_data():
mi = Series(np.arange(5).astype(np.float64),index=MultiIndex.from_tuples(tuple(zip(*[[1,1,2,2,2],
[3,4,3,4,5]])),
names=['one','two'])),
- dup=Series(np.arange(5).astype(np.float64), index=['A', 'B', 'C', 'D', 'A']))
+ dup=Series(np.arange(5).astype(np.float64), index=['A', 'B', 'C', 'D', 'A']),
+ cat=Series(Categorical(['foo', 'bar', 'baz'])))
frame = dict(float = DataFrame(dict(A = series['float'], B = series['float'] + 1)),
int = DataFrame(dict(A = series['int'] , B = series['int'] + 1)),
@@ -95,7 +96,11 @@ def create_data():
['one','two','one','two','three']])),
names=['first','second'])),
dup=DataFrame(np.arange(15).reshape(5, 3).astype(np.float64),
- columns=['A', 'B', 'A']))
+ columns=['A', 'B', 'A']),
+ cat_onecol=DataFrame(dict(A=Categorical(['foo', 'bar']))),
+ cat_and_float=DataFrame(dict(A=Categorical(['foo', 'bar', 'baz']),
+ B=np.arange(3))),
+ )
panel = dict(float = Panel(dict(ItemA = frame['float'], ItemB = frame['float']+1)),
dup = Panel(np.arange(30).reshape(3, 5, 2).astype(np.float64),
items=['A', 'B', 'A']))
diff --git a/pandas/tests/data/categorical_0_14_1.pickle b/pandas/tests/data/categorical_0_14_1.pickle
new file mode 100644
index 0000000000000..94f882b2f3027
--- /dev/null
+++ b/pandas/tests/data/categorical_0_14_1.pickle
@@ -0,0 +1,94 @@
+ccopy_reg
+_reconstructor
+p0
+(cpandas.core.categorical
+Categorical
+p1
+c__builtin__
+object
+p2
+Ntp3
+Rp4
+(dp5
+S'_levels'
+p6
+cnumpy.core.multiarray
+_reconstruct
+p7
+(cpandas.core.index
+Index
+p8
+(I0
+tp9
+S'b'
+p10
+tp11
+Rp12
+((I1
+(I4
+tp13
+cnumpy
+dtype
+p14
+(S'O8'
+p15
+I0
+I1
+tp16
+Rp17
+(I3
+S'|'
+p18
+NNNI-1
+I-1
+I63
+tp19
+bI00
+(lp20
+S'a'
+p21
+ag10
+aS'c'
+p22
+aS'd'
+p23
+atp24
+(Ntp25
+tp26
+bsS'labels'
+p27
+g7
+(cnumpy
+ndarray
+p28
+(I0
+tp29
+g10
+tp30
+Rp31
+(I1
+(I3
+tp32
+g14
+(S'i8'
+p33
+I0
+I1
+tp34
+Rp35
+(I3
+S'<'
+p36
+NNNI-1
+I-1
+I0
+tp37
+bI00
+S'\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00'
+p38
+tp39
+bsS'name'
+p40
+S'foobar'
+p41
+sb.
\ No newline at end of file
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index a2643b38e4133..03c73232f13bb 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -2,6 +2,8 @@
from datetime import datetime
from pandas.compat import range, lrange, u
+import os
+import pickle
import re
from distutils.version import LooseVersion
@@ -21,16 +23,6 @@ def setUp(self):
self.factor = Categorical.from_array(['a', 'b', 'b', 'a',
'a', 'c', 'c', 'c'])
- def assert_categorical_equal(self, res, exp):
- if not com.array_equivalent(res.categories, exp.categories):
- raise AssertionError('categories not equivalent: {0} vs {1}.'.format(res.categories,
- exp.categories))
- if not com.array_equivalent(res.codes, exp.codes):
- raise AssertionError('codes not equivalent: {0} vs {1}.'.format(res.codes,
- exp.codes))
- self.assertEqual(res.ordered, exp.ordered, "ordered not the same")
- self.assertEqual(res.name, exp.name, "name not the same")
-
def test_getitem(self):
self.assertEqual(self.factor[0], 'a')
self.assertEqual(self.factor[-1], 'c')
@@ -2268,6 +2260,21 @@ def get_dir(s):
results = get_dir(s)
tm.assert_almost_equal(results,list(sorted(set(ok_for_cat))))
+ def test_pickle_v0_14_1(self):
+ cat = pd.Categorical(values=['a', 'b', 'c'],
+ levels=['a', 'b', 'c', 'd'],
+ name='foobar', ordered=False)
+ pickle_path = os.path.join(tm.get_data_path(),
+ 'categorical_0_14_1.pickle')
+ # This code was executed once on v0.14.1 to generate the pickle:
+ #
+ # cat = Categorical(labels=np.arange(3), levels=['a', 'b', 'c', 'd'],
+ # name='foobar')
+ # with open(pickle_path, 'wb') as f: pickle.dump(cat, f)
+ #
+ self.assert_categorical_equal(cat, pd.read_pickle(pickle_path))
+
+
if __name__ == '__main__':
import nose
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py
index a523df4cc2461..5bc7558efb471 100644
--- a/pandas/tests/test_internals.py
+++ b/pandas/tests/test_internals.py
@@ -11,7 +11,7 @@
import pandas.util.testing as tm
import pandas as pd
from pandas.util.testing import (
- assert_almost_equal, assert_frame_equal, randn)
+ assert_almost_equal, assert_frame_equal, randn, assert_series_equal)
from pandas.compat import zip, u
@@ -363,6 +363,15 @@ def test_non_unique_pickle(self):
mgr2 = self.round_trip_pickle(mgr)
assert_frame_equal(DataFrame(mgr), DataFrame(mgr2))
+ def test_categorical_block_pickle(self):
+ mgr = create_mgr('a: category')
+ mgr2 = self.round_trip_pickle(mgr)
+ assert_frame_equal(DataFrame(mgr), DataFrame(mgr2))
+
+ smgr = create_single_mgr('category')
+ smgr2 = self.round_trip_pickle(smgr)
+ assert_series_equal(Series(smgr), Series(smgr2))
+
def test_get_scalar(self):
for item in self.mgr.items:
for i, index in enumerate(self.mgr.axes[1]):
diff --git a/pandas/util/testing.py b/pandas/util/testing.py
index d8cc39908a31f..b34bcc3c12890 100644
--- a/pandas/util/testing.py
+++ b/pandas/util/testing.py
@@ -121,6 +121,16 @@ def assert_numpy_array_equivalent(self, np_array, assert_equal, strict_nan=False
return
raise AssertionError('{0} is not equivalent to {1}.'.format(np_array, assert_equal))
+ def assert_categorical_equal(self, res, exp):
+ if not array_equivalent(res.categories, exp.categories):
+ raise AssertionError('categories not equivalent: {0} vs {1}.'.format(res.categories,
+ exp.categories))
+ if not array_equivalent(res.codes, exp.codes):
+ raise AssertionError('codes not equivalent: {0} vs {1}.'.format(res.codes,
+ exp.codes))
+ self.assertEqual(res.ordered, exp.ordered, "ordered not the same")
+ self.assertEqual(res.name, exp.name, "name not the same")
+
def assertIs(self, first, second, msg=''):
"""Checks that 'first' is 'second'"""
a, b = first, second
| This should fix #8518.
Apparently, `NonConsolidatableMixIn.__init__` was copied from a pre-`BlockPlacement` version of `SparseBlock.__init__` which was incompatible with placement being a slice. The current one is, so I moved it to NonConsolidatableMixIn class almost verbatim.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8519 | 2014-10-09T11:21:56Z | 2014-10-10T12:50:13Z | 2014-10-10T12:50:13Z | 2014-10-10T13:17:54Z |
ENH: axvlines - boolean option to parallel_coordinates plot | diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt
index 23ed1a083a965..dfbfd33232db8 100644
--- a/doc/source/whatsnew/v0.15.2.txt
+++ b/doc/source/whatsnew/v0.15.2.txt
@@ -80,6 +80,7 @@ Enhancements
- ``Series`` now works with map objects the same way as generators (:issue:`8909`).
- Added context manager to ``HDFStore`` for automatic closing (:issue:`8791`).
- ``to_datetime`` gains an ``exact`` keyword to allow for a format to not require an exact match for a provided format string (if its ``False). ``exact`` defaults to ``True`` (meaning that exact matching is still the default) (:issue:`8904`)
+- Added ``axvlines`` boolean option to parallel_coordinates plot function, determines whether vertical lines will be printed, default is True
.. _whatsnew_0152.performance:
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 1c998ca2f0a60..f39e1218a5a5b 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -2354,7 +2354,9 @@ def test_parallel_coordinates(self):
df = self.iris
- _check_plot_works(parallel_coordinates, df, 'Name')
+ ax = _check_plot_works(parallel_coordinates, df, 'Name')
+ nlines = len(ax.get_lines())
+ nxticks = len(ax.xaxis.get_ticklabels())
rgba = ('#556270', '#4ECDC4', '#C7F464')
ax = _check_plot_works(parallel_coordinates, df, 'Name', color=rgba)
@@ -2368,6 +2370,9 @@ def test_parallel_coordinates(self):
cmaps = lmap(cm.jet, np.linspace(0, 1, df['Name'].nunique()))
self._check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df['Name'][:10])
+ ax = _check_plot_works(parallel_coordinates, df, 'Name', axvlines=False)
+ assert len(ax.get_lines()) == (nlines - nxticks)
+
colors = ['b', 'g', 'r']
df = DataFrame({"A": [1, 2, 3],
"B": [1, 2, 3],
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index b55f0f0d9c61f..b9a96ee262101 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -581,7 +581,7 @@ def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds):
@deprecate_kwarg(old_arg_name='data', new_arg_name='frame')
def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
use_columns=False, xticks=None, colormap=None,
- **kwds):
+ axvlines=True, **kwds):
"""Parallel coordinates plotting.
Parameters
@@ -601,6 +601,8 @@ def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
A list of values to use for xticks
colormap: str or matplotlib colormap, default None
Colormap to use for line colors.
+ axvlines: bool, optional
+ If true, vertical lines will be added at each xtick
kwds: keywords
Options to pass to matplotlib plotting method
@@ -665,8 +667,9 @@ def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
else:
ax.plot(x, y, color=colors[kls], **kwds)
- for i in x:
- ax.axvline(i, linewidth=1, color='black')
+ if axvlines:
+ for i in x:
+ ax.axvline(i, linewidth=1, color='black')
ax.set_xticks(x)
ax.set_xticklabels(df.columns)
| Determines whether vertical lines will be added to parallel_coordinates plot. I was using parallel coordinates to make a seasonality chart - plotting years on top of each other (days/months of year on x-axis). With that many xticks, the vertical lines were overwhelming. It's possible to remove the lines after the fact, but without specific line identifiers, it isn't a straight forward process. However, preventing them from being added is a one-liner...
| https://api.github.com/repos/pandas-dev/pandas/pulls/8513 | 2014-10-08T21:22:27Z | 2014-12-05T20:16:33Z | 2014-12-05T20:16:33Z | 2015-09-03T15:25:02Z |
BUG: Suppress FutureWarning when comparing object arrays | diff --git a/doc/source/basics.rst b/doc/source/basics.rst
index bb65312f053f3..49959b1e4270f 100644
--- a/doc/source/basics.rst
+++ b/doc/source/basics.rst
@@ -317,6 +317,16 @@ locations treated as equal.
(df+df).equals(df*2)
+Note that the Series or DataFrame index needs to be in the same order for
+equality to be True:
+
+.. ipython:: python
+
+ df = DataFrame({'col':['foo', 0, np.nan]})
+ df2 = DataFrame({'col':[np.nan, 0, 'foo']}, index=[2,1,0])
+ df.equals(df2)
+ df.equals(df2.sort())
+
Combining overlapping data sets
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt
index b48f555f9691a..64ca1612f00c1 100644
--- a/doc/source/v0.13.1.txt
+++ b/doc/source/v0.13.1.txt
@@ -121,9 +121,10 @@ API changes
.. ipython:: python
- df = DataFrame({'col':['foo', 0, np.nan]}).sort()
+ df = DataFrame({'col':['foo', 0, np.nan]})
df2 = DataFrame({'col':[np.nan, 0, 'foo']}, index=[2,1,0])
- df.equals(df)
+ df.equals(df2)
+ df.equals(df2.sort())
import pandas.core.common as com
com.array_equivalent(np.array([0, np.nan]), np.array([0, np.nan]))
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index d972edeb2bbb3..af47ee878b1c3 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -1110,3 +1110,4 @@ Bug Fixes
- Regression in ``NDFrame.loc`` indexing when rows/columns were converted to Float64Index if target was an empty list/ndarray (:issue:`7774`)
- Bug in ``Series`` that allows it to be indexed by a ``DataFrame`` which has unexpected results. Such indexing is no longer permitted (:issue:`8444`)
- Bug in item assignment of a ``DataFrame`` with multi-index columns where right-hand-side columns were not aligned (:issue:`7655`)
+- Suppress FutureWarning generated by NumPy when comparing object arrays containing NaN for equality (:issue:`7065`)
diff --git a/pandas/core/common.py b/pandas/core/common.py
index a3698c569b8b3..da512dc56eaef 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -406,6 +406,7 @@ def array_equivalent(left, right, strict_nan=False):
>>> array_equivalent(np.array([1, nan, 2]), np.array([1, 2, nan]))
False
"""
+
left, right = np.asarray(left), np.asarray(right)
if left.shape != right.shape: return False
@@ -414,8 +415,8 @@ def array_equivalent(left, right, strict_nan=False):
if not strict_nan:
# pd.isnull considers NaN and None to be equivalent.
- return ((left == right) | (pd.isnull(left) & pd.isnull(right))).all()
-
+ return lib.array_equivalent_object(left.ravel(), right.ravel())
+
for left_value, right_value in zip(left, right):
if left_value is tslib.NaT and right_value is not tslib.NaT:
return False
@@ -426,7 +427,6 @@ def array_equivalent(left, right, strict_nan=False):
else:
if left_value != right_value:
return False
-
return True
# NaNs can occur in float and complex arrays.
diff --git a/pandas/core/index.py b/pandas/core/index.py
index f87b7e982b332..b9f1a06b171ed 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -1047,7 +1047,7 @@ def equals(self, other):
if type(other) != Index:
return other.equals(self)
- return array_equivalent(self, other)
+ return array_equivalent(_values_from_object(self), _values_from_object(other))
def identical(self, other):
"""Similar to equals, but check that other comparable attributes are
@@ -2260,7 +2260,7 @@ def equals(self, other):
# return False
try:
- return array_equivalent(self, other)
+ return array_equivalent(_values_from_object(self), _values_from_object(other))
except TypeError:
# e.g. fails in numpy 1.6 with DatetimeIndex #1681
return False
@@ -4175,7 +4175,8 @@ def equals(self, other):
return True
if not isinstance(other, MultiIndex):
- return array_equivalent(self.values, _ensure_index(other))
+ return array_equivalent(self.values,
+ _values_from_object(_ensure_index(other)))
if self.nlevels != other.nlevels:
return False
diff --git a/pandas/lib.pyx b/pandas/lib.pyx
index 7a90072b2410e..a845b9c90865b 100644
--- a/pandas/lib.pyx
+++ b/pandas/lib.pyx
@@ -330,6 +330,26 @@ def list_to_object_array(list obj):
return arr
+@cython.wraparound(False)
+@cython.boundscheck(False)
+def array_equivalent_object(ndarray left, ndarray right):
+ cdef Py_ssize_t i, n
+ cdef object lobj, robj
+
+ n = len(left)
+ for i from 0 <= i < n:
+ lobj = left[i]
+ robj = right[i]
+
+ # we are either not equal or both nan
+ # I think None == None will be true here
+ if lobj != robj:
+ if checknull(lobj) and checknull(robj):
+ continue
+ return False
+ return True
+
+
@cython.wraparound(False)
@cython.boundscheck(False)
def fast_unique(ndarray[object] values):
| Fixes #7065
| https://api.github.com/repos/pandas-dev/pandas/pulls/8512 | 2014-10-08T20:55:57Z | 2014-10-10T01:17:56Z | 2014-10-10T01:17:56Z | 2014-10-30T11:20:22Z |
DOC: fix example sql chunksize | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 5490e666904f9..70d5c195233c3 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -3421,7 +3421,7 @@ Specifying this will return an iterator through chunks of the query result:
.. ipython:: python
- for chunk in pd.read_sql_query("SELECT * FROM data_chunks", engine, chunksize):
+ for chunk in pd.read_sql_query("SELECT * FROM data_chunks", engine, chunksize=5):
print(chunk)
You can also run a plain query without creating a dataframe with
| https://api.github.com/repos/pandas-dev/pandas/pulls/8510 | 2014-10-08T19:45:27Z | 2014-10-08T20:14:52Z | 2014-10-08T20:14:52Z | 2014-10-08T20:14:52Z | |
DOC: Update ecosystem.rst: Add IDE, IPython, qgrid, Spyder, API, quandl, Out-of-core, Blaze | diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst
index c60f9ec9103e5..e5afe1db9417f 100644
--- a/doc/source/ecosystem.rst
+++ b/doc/source/ecosystem.rst
@@ -18,6 +18,7 @@ tools in the PyData space.
We'd like to make it easier for users to find these project, if you know of other
substantial projects that you feel should be on this list, please let us know.
+
.. _ecosystem.stats:
Statistics and Machine Learning
@@ -34,7 +35,8 @@ Statsmodels leverages pandas objects as the underlying data container for comput
`sklearn-pandas <https://github.com/paulgb/sklearn-pandas>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Use pandas DataFrames in your scikit-learn ML pipeline.
+Use pandas DataFrames in your `scikit-learn <http://scikit-learn.org/>`__
+ML pipeline.
@@ -43,12 +45,13 @@ Use pandas DataFrames in your scikit-learn ML pipeline.
Visualization
-------------
-`Vincent <https://github.com/wrobstory/vincent>`__
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+`Bokeh <http://bokeh.pydata.org>`__
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-The `Vincent <https://github.com/wrobstory/vincent>`__ project leverages `Vega <https://github.com/trifacta/vega>`__
-(that in turn, leverages `d3 <http://d3js.org/>`__) to create plots . It has great support
-for pandas data objects.
+Bokeh is a Python interactive visualization library for large datasets that natively uses
+the latest web technologies. Its goal is to provide elegant, concise construction of novel
+graphics in the style of Protovis/D3, while delivering high-performance interactivity over
+large data to thin clients.
`yhat/ggplot <https://github.com/yhat/ggplot>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -70,13 +73,63 @@ to cover. The `Seaborn <https://github.com/mwaskom/seaborn>`__ project builds on
and `matplotlib <http://matplotlib.org>`__ to provide easy plotting of data which extends to
more advanced types of plots then those offered by pandas.
-`Bokeh <http://bokeh.pydata.org>`__
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+`Vincent <https://github.com/wrobstory/vincent>`__
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The `Vincent <https://github.com/wrobstory/vincent>`__ project leverages `Vega <https://github.com/trifacta/vega>`__
+(that in turn, leverages `d3 <http://d3js.org/>`__) to create plots . It has great support
+for pandas data objects.
+
+
+.. _ecosystem.ide:
+
+IDE
+------
+
+`IPython <http://ipython.org/documentation.html>`__
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+IPython is an interactive command shell and distributed computing
+environment.
+IPython Notebook is a web application for creating IPython notebooks.
+An IPython notebook is a JSON document containing an ordered list
+of input/output cells which can contain code, text, mathematics, plots
+and rich media.
+IPython notebooks can be converted to a number of open standard output formats
+(HTML, HTML presentation slides, LaTeX, PDF, ReStructuredText, Markdown,
+Python) through 'Download As' in the web interface and ``ipython nbconvert``
+in a shell.
+
+Pandas DataFrames implement ``_repr_html_`` methods
+which are utilized by IPython Notebook for displaying
+(abbreviated) HTML tables. (Note: HTML tables may or may not be
+compatible with non-HTML IPython output formats.)
+
+`quantopian/qgrid <https://github.com/quantopian/qgrid>`__
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+qgrid is "an interactive grid for sorting and filtering
+DataFrames in IPython Notebook" built with SlickGrid.
+
+`Spyder <https://code.google.com/p/spyderlib/>`__
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Spyder is a cross-platform Qt-based open-source Python IDE with
+editing, testing, debugging, and introspection features.
+Spyder can now introspect and display Pandas DataFrames and show
+both "column wise min/max and global min/max coloring."
+
+
+.. _ecosystem.api:
+
+API
+-----
+
+`quandl/Python <https://github.com/quandl/Python>`_
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Quandl API for Python wraps the Quandl REST API to return
+Pandas DataFrames with timeseries indexes.
-Bokeh is a Python interactive visualization library for large datasets that natively uses
-the latest web technologies. Its goal is to provide elegant, concise construction of novel
-graphics in the style of Protovis/D3, while delivering high-performance interactivity over
-large data to thin clients.
.. _ecosystem.domain:
@@ -97,3 +150,16 @@ xray brings the labeled data power of pandas to the physical sciences by
providing N-dimensional variants of the core pandas data structures. It aims to
provide a pandas-like and pandas-compatible toolkit for analytics on multi-
dimensional arrays, rather than the tabular data for which pandas excels.
+
+
+.. _ecosystem.out-of-core:
+
+Out-of-core
+-------------
+
+`Blaze <http://blaze.pydata.org/>`__
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Blaze provides a standard API for doing computations with various
+in-memory and on-disk backends: NumPy, Pandas, SQLAlchemy, MongoDB, PyTables,
+PySpark.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8507 | 2014-10-08T10:58:17Z | 2014-10-13T14:20:11Z | 2014-10-13T14:20:11Z | 2014-10-13T14:21:33Z | |
COMPAT: matplotlib 1.4.0 version compat (GH8502) | diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 566f8a133a2c2..1793d6806be83 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -33,7 +33,7 @@ def _skip_if_mpl_14_or_dev_boxplot():
# Boxplot failures on 1.4 and 1.4.1
# Don't need try / except since that's done at class level
import matplotlib
- if matplotlib.__version__ >= LooseVersion('1.4'):
+ if str(matplotlib.__version__) >= LooseVersion('1.4'):
raise nose.SkipTest("Matplotlib Regression in 1.4 and current dev.")
@@ -72,7 +72,7 @@ def setUp(self):
'weight': random.normal(161, 32, size=n),
'category': random.randint(4, size=n)})
- if mpl.__version__ >= LooseVersion('1.4'):
+ if str(mpl.__version__) >= LooseVersion('1.4'):
self.bp_n_objects = 7
else:
self.bp_n_objects = 8
| closes #8502
| https://api.github.com/repos/pandas-dev/pandas/pulls/8504 | 2014-10-07T19:18:10Z | 2014-10-07T19:57:11Z | 2014-10-07T19:57:10Z | 2014-10-07T19:57:11Z |
Raise more specific exception on concat([None]) | diff --git a/pandas/tools/merge.py b/pandas/tools/merge.py
index c9935bf398cda..8fddfdda797c6 100644
--- a/pandas/tools/merge.py
+++ b/pandas/tools/merge.py
@@ -41,7 +41,7 @@ def merge(left, right, how='inner', on=None, left_on=None, right_on=None,
merge.__doc__ = _merge_doc % '\nleft : DataFrame'
-class MergeError(Exception):
+class MergeError(ValueError):
pass
@@ -679,7 +679,7 @@ def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
If a dict is passed, the sorted keys will be used as the `keys`
argument, unless it is passed, in which case the values will be
selected (see below). Any None objects will be dropped silently unless
- they are all None in which case an Exception will be raised
+ they are all None in which case a ValueError will be raised
axis : {0, 1, ...}, default 0
The axis to concatenate along
join : {'inner', 'outer'}, default 'outer'
@@ -764,7 +764,7 @@ def __init__(self, objs, axis=0, join='outer', join_axes=None,
keys = clean_keys
if len(objs) == 0:
- raise Exception('All objects passed were None')
+ raise ValueError('All objects passed were None')
# consolidate data & figure out what our result ndim is going to be
ndims = set()
diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py
index 89ff07bb7fa4c..c6335f623fa41 100644
--- a/pandas/tools/tests/test_merge.py
+++ b/pandas/tools/tests/test_merge.py
@@ -2122,7 +2122,7 @@ def test_concat_exclude_none(self):
pieces = [df[:5], None, None, df[5:]]
result = concat(pieces)
tm.assert_frame_equal(result, df)
- self.assertRaises(Exception, concat, [None, None])
+ self.assertRaises(ValueError, concat, [None, None])
def test_concat_datetime64_block(self):
from pandas.tseries.index import date_range
| More specific exception allows for a safer, more explicit catch by a caller.
ConcatenationError follows the pattern of MergeError which is used in the same file when something is wrong with a caller's inputs to merge().
| https://api.github.com/repos/pandas-dev/pandas/pulls/8501 | 2014-10-07T16:45:26Z | 2014-10-10T12:17:40Z | null | 2014-10-10T12:17:40Z |
WIP/CI: add appveyor support | diff --git a/appveyor.yml b/appveyor.yml
new file mode 100644
index 0000000000000..2a5597b380979
--- /dev/null
+++ b/appveyor.yml
@@ -0,0 +1,35 @@
+environment:
+ global:
+ # SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the
+ # /E:ON and /V:ON options are not enabled in the batch script intepreter
+ # See: http://stackoverflow.com/a/13751649/163740
+ CMD_IN_ENV: "cmd /E:ON /V:ON /C .\\ci\\run_with_env.cmd"
+
+ matrix:
+ - PYTHON: "C:\\Python27_32"
+ PYTHON_VERSION: "2.7"
+ PYTHON_ARCH: "32"
+
+ - PYTHON: "C:\\Python27_64"
+ PYTHON_VERSION: "2.7"
+ PYTHON_ARCH: "64"
+
+ - PYTHON: "C:\\Python34_32"
+ PYTHON_VERSION: "3.4"
+ PYTHON_ARCH: "32"
+
+ - PYTHON: "C:\\Python34_64"
+ PYTHON_VERSION: "3.4"
+ PYTHON_ARCH: "64"
+
+install:
+ # this installs the appropriate Miniconda (Py2/Py3, 32/64 bit),
+ # as well as pip, conda-build, and the binstar CLI
+ - powershell .\\ci\\install_appveyor.ps1
+ - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
+
+build: false
+
+test_script:
+ - "%CMD_IN_ENV% %PYTHON%/python.exe setup.py build_ext --inplace"
+ - "%PYTHON%/Scripts/nosetests -A \"not slow and not network and not disabled\" pandas"
diff --git a/ci/install_appveyor.ps1 b/ci/install_appveyor.ps1
new file mode 100644
index 0000000000000..756e39f6b57af
--- /dev/null
+++ b/ci/install_appveyor.ps1
@@ -0,0 +1,133 @@
+# Sample script to install Miniconda under Windows
+# Authors: Olivier Grisel, Jonathan Helmus and Kyle Kastner, Robert McGibbon
+# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/
+
+$MINICONDA_URL = "http://repo.continuum.io/miniconda/"
+
+
+function DownloadMiniconda ($python_version, $platform_suffix) {
+ $webclient = New-Object System.Net.WebClient
+ if ($python_version -match "3.4") {
+ $filename = "Miniconda3-3.5.5-Windows-" + $platform_suffix + ".exe"
+ } else {
+ $filename = "Miniconda-3.5.5-Windows-" + $platform_suffix + ".exe"
+ }
+ $url = $MINICONDA_URL + $filename
+
+ $basedir = $pwd.Path + "\"
+ $filepath = $basedir + $filename
+ if (Test-Path $filename) {
+ Write-Host "Reusing" $filepath
+ return $filepath
+ }
+
+ # Download and retry up to 3 times in case of network transient errors.
+ Write-Host "Downloading" $filename "from" $url
+ $retry_attempts = 2
+ for($i=0; $i -lt $retry_attempts; $i++){
+ try {
+ $webclient.DownloadFile($url, $filepath)
+ break
+ }
+ Catch [Exception]{
+ Start-Sleep 1
+ }
+ }
+ if (Test-Path $filepath) {
+ Write-Host "File saved at" $filepath
+ } else {
+ # Retry once to get the error message if any at the last try
+ $webclient.DownloadFile($url, $filepath)
+ }
+ return $filepath
+}
+
+function Start-Executable {
+ param(
+ [String] $FilePath,
+ [String[]] $ArgumentList
+ )
+ $OFS = " "
+ $process = New-Object System.Diagnostics.Process
+ $process.StartInfo.FileName = $FilePath
+ $process.StartInfo.Arguments = $ArgumentList
+ $process.StartInfo.UseShellExecute = $false
+ $process.StartInfo.RedirectStandardOutput = $true
+ if ( $process.Start() ) {
+ $output = $process.StandardOutput.ReadToEnd() `
+ -replace "\r\n$",""
+ if ( $output ) {
+ if ( $output.Contains("`r`n") ) {
+ $output -split "`r`n"
+ }
+ elseif ( $output.Contains("`n") ) {
+ $output -split "`n"
+ }
+ else {
+ $output
+ }
+ }
+ $process.WaitForExit()
+ & "$Env:SystemRoot\system32\cmd.exe" `
+ /c exit $process.ExitCode
+ }
+ }
+
+function InstallMiniconda ($python_version, $architecture, $python_home) {
+ Write-Host "Installing Python" $python_version "for" $architecture "bit architecture to" $python_home
+ if (Test-Path $python_home) {
+ Write-Host $python_home "already exists, skipping."
+ return $false
+ }
+ if ($architecture -match "32") {
+ $platform_suffix = "x86"
+ } else {
+ $platform_suffix = "x86_64"
+ }
+
+ $filepath = DownloadMiniconda $python_version $platform_suffix
+ Write-Host "Installing" $filepath "to" $python_home
+ $install_log = $python_home + ".log"
+ $args = "/S /D=$python_home"
+ Write-Host $filepath $args
+ Start-Process -FilePath $filepath -ArgumentList $args -Wait
+ if (Test-Path $python_home) {
+ Write-Host "Python $python_version ($architecture) installation complete"
+ } else {
+ Write-Host "Failed to install Python in $python_home"
+ Get-Content -Path $install_log
+ Exit 1
+ }
+}
+
+
+function InstallCondaPackages ($python_home, $spec) {
+ $conda_path = $python_home + "\Scripts\conda.exe"
+ $args = "install --yes --quiet " + $spec
+ Write-Host ("conda " + $args)
+ Start-Executable -FilePath "$conda_path" -ArgumentList $args
+}
+function InstallCondaPackagesFromFile ($python_home, $ver, $arch) {
+ $conda_path = $python_home + "\Scripts\conda.exe"
+ $args = "install --yes --quiet --file C:\projects\pandas\ci\requirements-" + $ver + "_" + $arch + ".txt"
+ Write-Host ("conda " + $args)
+ Start-Executable -FilePath "$conda_path" -ArgumentList $args
+}
+
+function UpdateConda ($python_home) {
+ $conda_path = $python_home + "\Scripts\conda.exe"
+ Write-Host "Updating conda..."
+ $args = "update --yes conda"
+ Write-Host $conda_path $args
+ Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait
+}
+
+
+function main () {
+ InstallMiniconda $env:PYTHON_VERSION $env:PYTHON_ARCH $env:PYTHON
+ UpdateConda $env:PYTHON
+ InstallCondaPackages $env:PYTHON "pip setuptools nose"
+ InstallCondaPackagesFromFile $env:PYTHON $env:PYTHON_VERSION $env:PYTHON_ARCH
+}
+
+main
\ No newline at end of file
diff --git a/ci/requirements-2.7_32.txt b/ci/requirements-2.7_32.txt
new file mode 100644
index 0000000000000..01b305bb6f21a
--- /dev/null
+++ b/ci/requirements-2.7_32.txt
@@ -0,0 +1,11 @@
+dateutil
+pytz
+xlwt
+numpy
+cython
+numexpr
+pytables
+matplotlib
+openpyxl
+xlrd
+scipy
diff --git a/ci/requirements-2.7_64.txt b/ci/requirements-2.7_64.txt
new file mode 100644
index 0000000000000..01b305bb6f21a
--- /dev/null
+++ b/ci/requirements-2.7_64.txt
@@ -0,0 +1,11 @@
+dateutil
+pytz
+xlwt
+numpy
+cython
+numexpr
+pytables
+matplotlib
+openpyxl
+xlrd
+scipy
diff --git a/ci/requirements-3.4_32.txt b/ci/requirements-3.4_32.txt
new file mode 100644
index 0000000000000..e9dfe9f0ee19e
--- /dev/null
+++ b/ci/requirements-3.4_32.txt
@@ -0,0 +1,10 @@
+dateutil
+pytz
+openpyxl
+xlrd
+numpy
+cython
+scipy
+numexpr
+pytables
+matplotlib
diff --git a/ci/requirements-3.4_64.txt b/ci/requirements-3.4_64.txt
new file mode 100644
index 0000000000000..e9dfe9f0ee19e
--- /dev/null
+++ b/ci/requirements-3.4_64.txt
@@ -0,0 +1,10 @@
+dateutil
+pytz
+openpyxl
+xlrd
+numpy
+cython
+scipy
+numexpr
+pytables
+matplotlib
diff --git a/ci/run_with_env.cmd b/ci/run_with_env.cmd
new file mode 100644
index 0000000000000..3a472bc836c30
--- /dev/null
+++ b/ci/run_with_env.cmd
@@ -0,0 +1,47 @@
+:: To build extensions for 64 bit Python 3, we need to configure environment
+:: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of:
+:: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1)
+::
+:: To build extensions for 64 bit Python 2, we need to configure environment
+:: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of:
+:: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0)
+::
+:: 32 bit builds do not require specific environment configurations.
+::
+:: Note: this script needs to be run with the /E:ON and /V:ON flags for the
+:: cmd interpreter, at least for (SDK v7.0)
+::
+:: More details at:
+:: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows
+:: http://stackoverflow.com/a/13751649/163740
+::
+:: Author: Olivier Grisel
+:: License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/
+@ECHO OFF
+
+SET COMMAND_TO_RUN=%*
+SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows
+
+SET MAJOR_PYTHON_VERSION="%PYTHON_VERSION:~0,1%"
+IF %MAJOR_PYTHON_VERSION% == "2" (
+ SET WINDOWS_SDK_VERSION="v7.0"
+) ELSE IF %MAJOR_PYTHON_VERSION% == "3" (
+ SET WINDOWS_SDK_VERSION="v7.1"
+) ELSE (
+ ECHO Unsupported Python version: "%MAJOR_PYTHON_VERSION%"
+ EXIT 1
+)
+
+IF "%PYTHON_ARCH%"=="64" (
+ ECHO Configuring Windows SDK %WINDOWS_SDK_VERSION% for Python %MAJOR_PYTHON_VERSION% on a 64 bit architecture
+ SET DISTUTILS_USE_SDK=1
+ SET MSSdk=1
+ "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION%
+ "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release
+ ECHO Executing: %COMMAND_TO_RUN%
+ call %COMMAND_TO_RUN% || EXIT 1
+) ELSE (
+ ECHO Using default MSVC build environment for 32 bit architecture
+ ECHO Executing: %COMMAND_TO_RUN%
+ call %COMMAND_TO_RUN% || EXIT 1
+)
| building using appveyor (windows CI)
closes #5561
https://ci.appveyor.com/project/jreback/pandas/build/1.0.455/job/2avadnw54tpv3lob
| https://api.github.com/repos/pandas-dev/pandas/pulls/8500 | 2014-10-07T16:31:32Z | 2014-10-07T21:52:42Z | 2014-10-07T21:52:42Z | 2014-10-07T21:52:42Z |
DOC: Another semicolon fix v0.15 | diff --git a/doc/source/release.rst b/doc/source/release.rst
index e43f83a8fa96d..0c62c4ee38efc 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -70,10 +70,6 @@ Highlights include:
See the :ref:`v0.15.0 Whatsnew <whatsnew_0150>` overview or the issue tracker on GitHub for an extensive list
of all API changes, enhancements and bugs that have been fixed in 0.15.0.
-This is a major release from 0.14.1 and includes a small number of API changes, several new features,
-enhancements, and performance improvements along with a large number of bug fixes. We recommend that all
-users upgrade to this version.
-
Thanks
~~~~~~
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 3cb7b7d5e8b69..e76a0e57c5e33 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -274,7 +274,7 @@ API changes
- ``Series.to_csv()`` now returns a string when ``path=None``, matching the behaviour of ``DataFrame.to_csv()`` (:issue:`8215`).
-- ``read_hdf`` now raises ``IOError`` when a file that doesn't exist is passed in. Previously, a new, empty file was created, and a ``KeyError`` raised (:issue `7715`).
+- ``read_hdf`` now raises ``IOError`` when a file that doesn't exist is passed in. Previously, a new, empty file was created, and a ``KeyError`` raised (:issue:`7715`).
- ``DataFrame.info()`` now ends its output with a newline character (:issue:`8114`)
- add ``copy=True`` argument to ``pd.concat`` to enable pass thru of complete blocks (:issue:`8252`)
@@ -387,7 +387,7 @@ Timezone API changes
- ``tz_localize`` now accepts the ``ambiguous`` keyword which allows for passing an array of bools
indicating whether the date belongs in DST or not, 'NaT' for setting transition times to NaT,
- 'infer' for inferring DST/non-DST, and 'raise' (default) for an AmbiguousTimeError to be raised. See :ref:`the docs<timeseries.timezone_ambiguous>` for more details (:issue:`7943`)
+ 'infer' for inferring DST/non-DST, and 'raise' (default) for an ``AmbiguousTimeError`` to be raised. See :ref:`the docs<timeseries.timezone_ambiguous>` for more details (:issue:`7943`)
- ``DataFrame.tz_localize`` and ``DataFrame.tz_convert`` now accepts an optional ``level`` argument
for localizing a specific level of a MultiIndex (:issue:`7846`)
@@ -696,7 +696,7 @@ Consruct a scalar
# a NaT
Timedelta('nan')
-Access fields for a Timedelta
+Access fields for a ``Timedelta``
.. ipython:: python
@@ -920,10 +920,10 @@ Bug Fixes
- Bug in checking of table name in ``read_sql`` in certain cases (:issue:`7826`).
- Bug in ``DataFrame.groupby`` where ``Grouper`` does not recognize level when frequency is specified (:issue:`7885`)
- Bug in multiindexes dtypes getting mixed up when DataFrame is saved to SQL table (:issue:`8021`)
-- Bug in Series 0-division with a float and integer operand dtypes (:issue:`7785`)
+- Bug in ``Series`` 0-division with a float and integer operand dtypes (:issue:`7785`)
- Bug in ``Series.astype("unicode")`` not calling ``unicode`` on the values correctly (:issue:`7758`)
- Bug in ``DataFrame.as_matrix()`` with mixed ``datetime64[ns]`` and ``timedelta64[ns]`` dtypes (:issue:`7778`)
-- Bug in ``HDFStore.select_column()`` not preserving UTC timezone info when selecting a DatetimeIndex (:issue:`7777`)
+- Bug in ``HDFStore.select_column()`` not preserving UTC timezone info when selecting a ``DatetimeIndex`` (:issue:`7777`)
- Bug in ``to_datetime`` when ``format='%Y%m%d'`` and ``coerce=True`` are specified, where previously an object array was returned (rather than
a coerced time-series with ``NaT``), (:issue:`7930`)
- Bug in ``DatetimeIndex`` and ``PeriodIndex`` in-place addition and subtraction cause different result from normal one (:issue:`6527`)
@@ -932,25 +932,25 @@ Bug Fixes
- Bug in multi-index slicing with missing indexers (:issue:`7866`)
- Bug in multi-index slicing with various edge cases (:issue:`8132`)
- Regression in multi-index indexing with a non-scalar type object (:issue:`7914`)
-- Bug in Timestamp comparisons with ``==`` and dtype of int64 (:issue:`8058`)
+- Bug in ``Timestamp`` comparisons with ``==`` and ``int64`` dtype (:issue:`8058`)
- Bug in pickles contains ``DateOffset`` may raise ``AttributeError`` when ``normalize`` attribute is reffered internally (:issue:`7748`)
-- Bug in Panel when using ``major_xs`` and ``copy=False`` is passed (deprecation warning fails because of missing ``warnings``) (:issue:`8152`).
+- Bug in ``Panel`` when using ``major_xs`` and ``copy=False`` is passed (deprecation warning fails because of missing ``warnings``) (:issue:`8152`).
- Bug in pickle deserialization that failed for pre-0.14.1 containers with dup items trying to avoid ambiguity
when matching block and manager items, when there's only one block there's no ambiguity (:issue:`7794`)
- Bug in putting a ``PeriodIndex`` into a ``Series`` would convert to ``int64`` dtype, rather than ``object`` of ``Periods`` (:issue:`7932`)
-- Bug in HDFStore iteration when passing a where (:issue:`8014`)
-- Bug in DataFrameGroupby.transform when transforming with a passed non-sorted key (:issue:`8046`, :issue:`8430`)
+- Bug in ``HDFStore`` iteration when passing a where (:issue:`8014`)
+- Bug in ``DataFrameGroupby.transform`` when transforming with a passed non-sorted key (:issue:`8046`, :issue:`8430`)
- Bug in repeated timeseries line and area plot may result in ``ValueError`` or incorrect kind (:issue:`7733`)
-- Bug in inference in a MultiIndex with ``datetime.date`` inputs (:issue:`7888`)
+- Bug in inference in a ``MultiIndex`` with ``datetime.date`` inputs (:issue:`7888`)
- Bug in ``get`` where an ``IndexError`` would not cause the default value to be returned (:issue:`7725`)
- Bug in ``offsets.apply``, ``rollforward`` and ``rollback`` may reset nanosecond (:issue:`7697`)
- Bug in ``offsets.apply``, ``rollforward`` and ``rollback`` may raise ``AttributeError`` if ``Timestamp`` has ``dateutil`` tzinfo (:issue:`7697`)
-- Bug in sorting a multi-index frame with a Float64Index (:issue:`8017`)
-- Bug in inconsistent panel setitem with a rhs of a DataFrame for alignment (:issue:`7763`)
+- Bug in sorting a multi-index frame with a ``Float64Index`` (:issue:`8017`)
+- Bug in inconsistent panel setitem with a rhs of a ``DataFrame`` for alignment (:issue:`7763`)
- Bug in ``is_superperiod`` and ``is_subperiod`` cannot handle higher frequencies than ``S`` (:issue:`7760`, :issue:`7772`, :issue:`7803`)
- Bug in 32-bit platforms with ``Series.shift`` (:issue:`8129`)
- Bug in ``PeriodIndex.unique`` returns int64 ``np.ndarray`` (:issue:`7540`)
-- Bug in groupby ``.apply`` with a non-affecting mutation in the function (:issue:`8467`)
+- Bug in ``groupby.apply`` with a non-affecting mutation in the function (:issue:`8467`)
- Bug in ``DataFrame.reset_index`` which has ``MultiIndex`` contains ``PeriodIndex`` or ``DatetimeIndex`` with tz raises ``ValueError`` (:issue:`7746`, :issue:`7793`)
@@ -995,7 +995,7 @@ Bug Fixes
return a non scalar value that appeared valid but wasn't (:issue:`7870`).
- Bug in ``date_range()``/``DatetimeIndex()`` when the timezone was inferred from input dates yet incorrect
times were returned when crossing DST boundaries (:issue:`7835`, :issue:`7901`).
-- Bug in ``to_excel()`` where a negative sign was being prepended to positive infinity and was absent for negative infinity (:issue`7949`)
+- Bug in ``to_excel()`` where a negative sign was being prepended to positive infinity and was absent for negative infinity (:issue:`7949`)
- Bug in area plot draws legend with incorrect ``alpha`` when ``stacked=True`` (:issue:`8027`)
- ``Period`` and ``PeriodIndex`` addition/subtraction with ``np.timedelta64`` results in incorrect internal representations (:issue:`7740`)
- Bug in ``Holiday`` with no offset or observance (:issue:`7987`)
@@ -1021,7 +1021,7 @@ Bug Fixes
``_read`` (:issue:`7927`).
- Bug in ``DataFrame.stack()`` when one of the column levels was a datelike (:issue:`8039`)
-- Bug in broadcasting numpy scalars with DataFrames (:issue:`8116`)
+- Bug in broadcasting numpy scalars with ``DataFrame`` (:issue:`8116`)
- Bug in ``pivot_table`` performed with nameless ``index`` and ``columns`` raises ``KeyError`` (:issue:`8103`)
@@ -1059,15 +1059,15 @@ Bug Fixes
- Bug in interpolation methods with the ``limit`` keyword when no values needed interpolating (:issue:`7173`).
- Bug where ``col_space`` was ignored in ``DataFrame.to_string()`` when ``header=False`` (:issue:`8230`).
- Bug in ``to_clipboard`` that would clip long column data (:issue:`8305`)
-- Bug in DataFrame terminal display: Setting max_column/max_rows to zero did not trigger auto-resizing of dfs to fit terminal width/height (:issue:`7180`).
+- Bug in ``DataFrame`` terminal display: Setting max_column/max_rows to zero did not trigger auto-resizing of dfs to fit terminal width/height (:issue:`7180`).
- Bug in OLS where running with "cluster" and "nw_lags" parameters did not work correctly, but also did not throw an error
(:issue:`5884`).
- Bug in ``DataFrame.dropna`` that interpreted non-existent columns in the subset argument as the 'last column' (:issue:`8303`)
-- Bug in Index.intersection on non-monotonic non-unique indexes (:issue:`8362`).
+- Bug in ``Index.intersection`` on non-monotonic non-unique indexes (:issue:`8362`).
- Bug in masked series assignment where mismatching types would break alignment (:issue:`8387`)
-- Bug in NDFrame.equals gives false negatives with dtype=object (:issue:`8437`)
+- Bug in ``NDFrame.equals`` gives false negatives with dtype=object (:issue:`8437`)
- Bug in assignment with indexer where type diversity would break alignment (:issue:`8258`)
- Bug in ``NDFrame.loc`` indexing when row/column names were lost when target was a list/ndarray (:issue:`6552`)
- Regression in ``NDFrame.loc`` indexing when rows/columns were converted to Float64Index if target was an empty list/ndarray (:issue:`7774`)
-- Bug in Series that allows it to be indexed by a DataFrame which has unexpected results. Such indexing is no longer permitted (:issue:`8444`)
-- Bug in item assignment of a DataFrame with multi-index columns where right-hand-side columns were not aligned (:issue:`7655`)
+- Bug in ``Series`` that allows it to be indexed by a ``DataFrame`` which has unexpected results. Such indexing is no longer permitted (:issue:`8444`)
+- Bug in item assignment of a ``DataFrame`` with multi-index columns where right-hand-side columns were not aligned (:issue:`7655`)
diff --git a/setup.py b/setup.py
index ec19e1931f9ce..7c01c84810b11 100755
--- a/setup.py
+++ b/setup.py
@@ -189,7 +189,7 @@ def build_extensions(self):
MAJOR = 0
MINOR = 15
MICRO = 0
-ISRELEASED = True
+ISRELEASED = False
VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
QUALIFIER = 'rc1'
| Sorry for basically duplicate pr, noticed this one after.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8498 | 2014-10-07T15:40:33Z | 2014-10-07T17:43:45Z | null | 2014-10-07T17:43:45Z |
DOC/BUG:Added Missing Semicolon to Release Note v0.15 | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 3cb7b7d5e8b69..5dbb45876704c 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -274,7 +274,7 @@ API changes
- ``Series.to_csv()`` now returns a string when ``path=None``, matching the behaviour of ``DataFrame.to_csv()`` (:issue:`8215`).
-- ``read_hdf`` now raises ``IOError`` when a file that doesn't exist is passed in. Previously, a new, empty file was created, and a ``KeyError`` raised (:issue `7715`).
+- ``read_hdf`` now raises ``IOError`` when a file that doesn't exist is passed in. Previously, a new, empty file was created, and a ``KeyError`` raised (:issue:`7715`).
- ``DataFrame.info()`` now ends its output with a newline character (:issue:`8114`)
- add ``copy=True`` argument to ``pd.concat`` to enable pass thru of complete blocks (:issue:`8252`)
| Missed a semi-colon, here's the fix.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8497 | 2014-10-07T15:28:14Z | 2014-10-07T15:32:04Z | 2014-10-07T15:32:04Z | 2014-10-07T18:17:23Z |
DOC: fix notes in plot() docstring | diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 1774133dd4c9d..1d47c3781a7d7 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -2310,8 +2310,7 @@ def _plot(data, x=None, y=None, subplots=False,
Sort column names to determine plot ordering
secondary_y : boolean or sequence, default False
Whether to plot on the secondary y-axis
- If a list/tuple, which columns to plot on secondary y-axis
-"""
+ If a list/tuple, which columns to plot on secondary y-axis"""
series_unique = """label : label argument to provide to plot
secondary_y : boolean or sequence of ints, default False
If True then y-axis will be on the right"""
@@ -2328,9 +2327,8 @@ def _plot(data, x=None, y=None, subplots=False,
series_ax = """ax : matplotlib axes object
If not passed, uses gca()"""
-df_note = """- If `kind` = 'bar' or 'barh', you can specify relative alignments
- for bar plot layout by `position` keyword.
- From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)
+df_note = """- If `kind` = 'scatter' and the argument `c` is the name of a dataframe
+ column, the values of that column are used to color each point.
- If `kind` = 'hexbin', you can control the size of the bins with the
`gridsize` argument. By default, a histogram of the counts around each
`(x, y)` point is computed. You can specify alternative aggregations
@@ -2425,19 +2423,12 @@ def _plot(data, x=None, y=None, subplots=False,
Notes
-----
- If `kind` = 'hexbin', you can control the size of the bins with the
- `gridsize` argument. By default, a histogram of the counts around each
- `(x, y)` point is computed. You can specify alternative aggregations
- by passing values to the `C` and `reduce_C_function` arguments.
- `C` specifies the value at each `(x, y)` point and `reduce_C_function`
- is a function of one argument that reduces all the values in a bin to
- a single number (e.g. `mean`, `max`, `sum`, `std`).
-
- If `kind` = 'scatter' and the argument `c` is the name of a dataframe column,
- the values of that column are used to color each point.
- See matplotlib documentation online for more on this subject
+ - If `kind` = 'bar' or 'barh', you can specify relative alignments
+ for bar plot layout by `position` keyword.
+ From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)
%(klass_note)s
-
+
"""
@Appender(_shared_docs['plot'] % _shared_doc_df_kwargs)
| There was some repetition in the docstring note of `plot` since the refactor of the docstring (hexbin part) + scatter is only needed for dataframe docstring (not series)
| https://api.github.com/repos/pandas-dev/pandas/pulls/8493 | 2014-10-06T20:32:54Z | 2014-10-06T20:33:17Z | 2014-10-06T20:33:17Z | 2014-10-06T20:33:17Z |
BUG: searchsorted sorter issue with 32bit platforms (GH8490) | diff --git a/pandas/core/series.py b/pandas/core/series.py
index f313352ef9660..95a7b22b90338 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1429,6 +1429,9 @@ def searchsorted(self, v, side='left', sorter=None):
>>> x.searchsorted([1, 2], side='right', sorter=[0, 2, 1])
array([1, 3])
"""
+ if sorter is not None:
+ sorter = com._ensure_platform_int(sorter)
+
return self.values.searchsorted(Series(v).values, side=side,
sorter=sorter)
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 521eddbba2e09..d3f7414289053 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -6199,6 +6199,12 @@ def test_search_sorted_datetime64_list(self):
e = np.array([1, 2])
tm.assert_array_equal(r, e)
+ def test_searchsorted_sorter(self):
+ # GH8490
+ s = Series([3, 1, 2])
+ r = s.searchsorted([0, 3], sorter=np.argsort(s))
+ e = np.array([0, 2])
+ tm.assert_array_equal(r, e)
| Closes #8490
| https://api.github.com/repos/pandas-dev/pandas/pulls/8492 | 2014-10-06T20:21:42Z | 2014-10-06T21:58:41Z | 2014-10-06T21:58:40Z | 2014-10-06T22:01:43Z |
DOC: warning about copying for df.append/concat. Fixes #7967 | diff --git a/doc/source/merging.rst b/doc/source/merging.rst
index 922fb84c57a56..7d21ba4a3b694 100644
--- a/doc/source/merging.rst
+++ b/doc/source/merging.rst
@@ -51,7 +51,6 @@ takes a list or dict of homogeneously-typed objects and concatenates them with
some configurable handling of "what to do with the other axes":
::
-
concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
keys=None, levels=None, names=None, verify_integrity=False)
@@ -100,6 +99,18 @@ means that we can now do stuff like select out each chunk by key:
It's not a stretch to see how this can be very useful. More detail on this
functionality below.
+.. note::
+ It is worth noting however, that ``concat`` (and therefore ``append``) makes
+ a full copy of the data, and that constantly reusing this function can
+ create a signifcant performance hit. If you need to use the operation over
+ several datasets, use a list comprehension.
+
+::
+
+ frames = [ process_your_file(f) for f in files ]
+ result = pd.concat(frames)
+
+
Set logic on the other axes
~~~~~~~~~~~~~~~~~~~~~~~~~~~
| closes #7967
| https://api.github.com/repos/pandas-dev/pandas/pulls/8488 | 2014-10-06T16:00:32Z | 2014-10-06T17:09:18Z | 2014-10-06T17:09:18Z | 2014-10-06T17:13:37Z |
DOC: fix bunch of doc build errors | diff --git a/doc/source/api.rst b/doc/source/api.rst
index 4dd055bce0a0a..2e913d8aae4da 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -819,7 +819,6 @@ Reshaping, sorting, transposing
.. autosummary::
:toctree: generated/
- DataFrame.delevel
DataFrame.pivot
DataFrame.reorder_levels
DataFrame.sort
diff --git a/doc/source/index.rst.template b/doc/source/index.rst.template
index ccedaaa0429f0..ee779715bcb95 100644
--- a/doc/source/index.rst.template
+++ b/doc/source/index.rst.template
@@ -135,7 +135,6 @@ See the package overview for more detail about what's in the library.
timedeltas
categorical
visualization
- rplot
io
remote_data
enhancingperf
diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst
index 7494f21b3ba71..00058a650258b 100644
--- a/doc/source/indexing.rst
+++ b/doc/source/indexing.rst
@@ -106,9 +106,8 @@ of multi-axis indexing.
label based access and not positional access is supported.
Thus, in such cases, it's usually better to be explicit and use ``.iloc`` or ``.loc``.
- See more at :ref:`Advanced Indexing <advanced>`, :ref:`Advanced
- Hierarchical <advanced.advanced_hierarchical>` and :ref:`Fallback Indexing
- <advanced.fallback>`
+ See more at :ref:`Advanced Indexing <advanced>` and :ref:`Advanced
+ Hierarchical <advanced.advanced_hierarchical>`.
Getting values from an object with multi-axes selection uses the following
notation (using ``.loc`` as an example, but applies to ``.iloc`` and ``.ix`` as
diff --git a/doc/source/missing_data.rst b/doc/source/missing_data.rst
index 69afd861df325..4505d256d31f6 100644
--- a/doc/source/missing_data.rst
+++ b/doc/source/missing_data.rst
@@ -422,7 +422,7 @@ at the new values.
ser = Series(np.sort(np.random.uniform(size=100)))
# interpolate at new_index
- new_index = ser.index + Index([49.25, 49.5, 49.75, 50.25, 50.5, 50.75])
+ new_index = ser.index | Index([49.25, 49.5, 49.75, 50.25, 50.5, 50.75])
interp_s = ser.reindex(new_index).interpolate(method='pchip')
interp_s[49:51]
diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst
index 3285efadf8ad1..b0c979989411d 100644
--- a/doc/source/visualization.rst
+++ b/doc/source/visualization.rst
@@ -689,7 +689,7 @@ See the `matplotlib pie documenation <http://matplotlib.org/api/pyplot_api.html#
plt.close('all')
-.. _visualization.missing_data
+.. _visualization.missing_data:
Plotting with Missing Data
--------------------------
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 2e107e0b0e935..9ce0b816af0db 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -918,8 +918,8 @@ def cumcount(self, **kwargs):
ascending : bool, default True
If False, number in reverse, from length of group - 1 to 0.
- Example
- -------
+ Examples
+ --------
>>> df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']],
... columns=['A'])
@@ -963,8 +963,8 @@ def head(self, n=5):
Essentially equivalent to ``.apply(lambda x: x.head(n))``,
except ignores as_index flag.
- Example
- -------
+ Examples
+ --------
>>> df = DataFrame([[1, 2], [1, 4], [5, 6]],
columns=['A', 'B'])
@@ -990,8 +990,8 @@ def tail(self, n=5):
Essentially equivalent to ``.apply(lambda x: x.tail(n))``,
except ignores as_index flag.
- Example
- -------
+ Examples
+ --------
>>> df = DataFrame([[1, 2], [1, 4], [5, 6]],
columns=['A', 'B'])
@@ -2452,8 +2452,8 @@ def filter(self, func, dropna=True, *args, **kwargs):
dropna : Drop groups that do not pass the filter. True by default;
if False, groups that evaluate False are filled with NaNs.
- Example
- -------
+ Examples
+ --------
>>> grouped.filter(lambda x: x.mean() > 0)
Returns
@@ -3083,7 +3083,7 @@ def filter(self, func, dropna=True, *args, **kwargs):
Each subframe is endowed the attribute 'name' in case you need to know
which group you are working on.
- Example
+ Examples
--------
>>> grouped = df.groupby(lambda x: mapping[x])
>>> grouped.filter(lambda x: x['A'].sum() + x['B'].sum() > 0)
diff --git a/pandas/io/json.py b/pandas/io/json.py
index 4ed325df9a747..9e8ef74545ef2 100644
--- a/pandas/io/json.py
+++ b/pandas/io/json.py
@@ -573,7 +573,9 @@ def nested_to_record(ds, prefix="", level=0):
-------
d - dict or list of dicts, matching `ds`
- Example:
+ Examples
+ --------
+
IN[52]: nested_to_record(dict(flat1=1,dict1=dict(c=1,d=2),
nested=dict(e=dict(c=1,d=2),d=2)))
Out[52]:
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 80db990a25ea7..1774133dd4c9d 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -2328,10 +2328,10 @@ def _plot(data, x=None, y=None, subplots=False,
series_ax = """ax : matplotlib axes object
If not passed, uses gca()"""
-df_note = """- If `kind`='bar' or 'barh', you can specify relative alignments
+df_note = """- If `kind` = 'bar' or 'barh', you can specify relative alignments
for bar plot layout by `position` keyword.
From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)
- - If `kind`='hexbin', you can control the size of the bins with the
+ - If `kind` = 'hexbin', you can control the size of the bins with the
`gridsize` argument. By default, a histogram of the counts around each
`(x, y)` point is computed. You can specify alternative aggregations
by passing values to the `C` and `reduce_C_function` arguments.
@@ -2425,7 +2425,7 @@ def _plot(data, x=None, y=None, subplots=False,
Notes
-----
- If `kind`='hexbin', you can control the size of the bins with the
+ If `kind` = 'hexbin', you can control the size of the bins with the
`gridsize` argument. By default, a histogram of the counts around each
`(x, y)` point is computed. You can specify alternative aggregations
by passing values to the `C` and `reduce_C_function` arguments.
@@ -2433,10 +2433,11 @@ def _plot(data, x=None, y=None, subplots=False,
is a function of one argument that reduces all the values in a bin to
a single number (e.g. `mean`, `max`, `sum`, `std`).
- If `kind`='scatter' and the argument `c` is the name of a dataframe column,
+ If `kind` = 'scatter' and the argument `c` is the name of a dataframe column,
the values of that column are used to color each point.
- See matplotlib documentation online for more on this subject
%(klass_note)s
+
"""
@Appender(_shared_docs['plot'] % _shared_doc_df_kwargs)
| https://api.github.com/repos/pandas-dev/pandas/pulls/8487 | 2014-10-06T14:47:19Z | 2014-10-06T15:09:27Z | 2014-10-06T15:09:27Z | 2014-10-06T15:09:27Z | |
[ENH] Add orient argument and split option to to_dict. (GH7840) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 2c1fc9c9a6eef..cec3148a1f9fa 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -767,6 +767,7 @@ Prior Version Deprecations/Changes
Deprecations
~~~~~~~~~~~~
+- The ``outtype`` argument to ``pd.DataFrame.to_dict`` has been deprecated in favor of ``orient``. (:issue:`7840`)
- The ``convert_dummies`` method has been deprecated in favor of
``get_dummies`` (:issue:`8140`)
- The ``infer_dst`` argument in ``tz_localize`` will be deprecated in favor of
@@ -849,7 +850,7 @@ Enhancements
idx
idx + pd.offsets.MonthEnd(3)
-
+- Added ``split`` as an option to the ``orient`` argument in ``pd.DataFrame.to_dict``. (:issue:`7840`)
- The ``get_dummies`` method can now be used on DataFrames. By default only
catagorical columns are encoded as 0's and 1's, while other columns are
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 8342c587ae4bb..2c172d6fe1af0 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -640,19 +640,25 @@ def from_dict(cls, data, orient='columns', dtype=None):
return cls(data, index=index, columns=columns, dtype=dtype)
- def to_dict(self, outtype='dict'):
- """
- Convert DataFrame to dictionary.
+ @deprecate_kwarg(old_arg_name='outtype', new_arg_name='orient')
+ def to_dict(self, orient='dict'):
+ """Convert DataFrame to dictionary.
Parameters
----------
- outtype : str {'dict', 'list', 'series', 'records'}
- Determines the type of the values of the dictionary. The
- default `dict` is a nested dictionary {column -> {index -> value}}.
- `list` returns {column -> list(values)}. `series` returns
- {column -> Series(values)}. `records` returns [{columns -> value}].
- Abbreviations are allowed.
+ orient : str {'dict', 'list', 'series', 'split', 'records'}
+ Determines the type of the values of the dictionary.
+
+ - dict (default) : dict like {column -> {index -> value}}
+ - list : dict like {column -> [values]}
+ - series : dict like {column -> Series(values)}
+ - split : dict like
+ {index -> [index], columns -> [columns], data -> [values]}
+ - records : list like
+ [{column -> value}, ... , {column -> value}]
+ Abbreviations are allowed. `s` indicates `series` and `sp`
+ indicates `split`.
Returns
-------
@@ -661,13 +667,17 @@ def to_dict(self, outtype='dict'):
if not self.columns.is_unique:
warnings.warn("DataFrame columns are not unique, some "
"columns will be omitted.", UserWarning)
- if outtype.lower().startswith('d'):
+ if orient.lower().startswith('d'):
return dict((k, v.to_dict()) for k, v in compat.iteritems(self))
- elif outtype.lower().startswith('l'):
+ elif orient.lower().startswith('l'):
return dict((k, v.tolist()) for k, v in compat.iteritems(self))
- elif outtype.lower().startswith('s'):
+ elif orient.lower().startswith('sp'):
+ return {'index': self.index.tolist(),
+ 'columns': self.columns.tolist(),
+ 'data': self.values.tolist()}
+ elif orient.lower().startswith('s'):
return dict((k, v) for k, v in compat.iteritems(self))
- elif outtype.lower().startswith('r'):
+ elif orient.lower().startswith('r'):
return [dict((k, v) for k, v in zip(self.columns, row))
for row in self.values]
else: # pragma: no cover
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 0dbca6f122b93..ba81d98510f5c 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -4037,6 +4037,13 @@ def test_to_dict(self):
for k2, v2 in compat.iteritems(v):
self.assertEqual(v2, recons_data[k][k2])
+ recons_data = DataFrame(test_data).to_dict("sp")
+
+ expected_split = {'columns': ['A', 'B'], 'index': ['1', '2', '3'],
+ 'data': [[1.0, '1'], [2.0, '2'], [nan, '3']]}
+
+ tm.assert_almost_equal(recons_data, expected_split)
+
recons_data = DataFrame(test_data).to_dict("r")
expected_records = [{'A': 1.0, 'B': '1'},
| closes #7840
Unlike the implementation offered in #7840, this version preserves the option to pass prefixes to the `orient` parameter.
I also rewrote the docstring to use the more readable list format from `pd.DataFrame.to_json`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8486 | 2014-10-06T14:34:21Z | 2014-10-06T19:56:16Z | null | 2014-10-06T20:10:08Z |
DOC: indexing.rst fixes w.r.t (GH8227) | diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst
index 7494f21b3ba71..8edd3e93759a6 100644
--- a/doc/source/indexing.rst
+++ b/doc/source/indexing.rst
@@ -1191,39 +1191,8 @@ The name, if set, will be shown in the console display:
df
df['A']
-
-Set operations on Index objects
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-.. _indexing.set_ops:
-
-The three main operations are ``union (|)``, ``intersection (&)``, and ``diff
-(-)``. These can be directly called as instance methods or used via overloaded
-operators:
-
-.. ipython:: python
-
- a = Index(['c', 'b', 'a'])
- b = Index(['c', 'e', 'd'])
- a.union(b)
- a | b
- a & b
- a - b
-
-Also available is the ``sym_diff (^)`` operation, which returns elements
-that appear in either ``idx1`` or ``idx2`` but not both. This is
-equivalent to the Index created by ``(idx1 - idx2) + (idx2 - idx1)``,
-with duplicates dropped.
-
-.. ipython:: python
-
- idx1 = Index([1, 2, 3, 4])
- idx2 = Index([2, 3, 4, 5])
- idx1.sym_diff(idx2)
- idx1 ^ idx2
-
-Setting index metadata (``name(s)``, ``levels``, ``labels``)
-------------------------------------------------------------
+Setting metadata
+~~~~~~~~~~~~~~~~
.. versionadded:: 0.13.0
@@ -1261,6 +1230,40 @@ See :ref:`Advanced Indexing <advanced>` for usage of MultiIndexes.
index.levels[1]
index.set_levels(["a", "b"], level=1)
+Set operations on Index objects
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. _indexing.set_ops:
+
+.. warning::
+
+ In 0.15.0. the set operations ``+`` and ``-`` were deprecated in order to provide these for numeric type operations on certain
+ index types. ``+`` can be replace by ``.union()`` or ``|``, and ``-`` by ``.difference()``.
+
+The two main operations are ``union (|)``, ``intersection (&)``
+These can be directly called as instance methods or used via overloaded
+operators. Difference is provided via the ``.difference()`` method.
+
+.. ipython:: python
+
+ a = Index(['c', 'b', 'a'])
+ b = Index(['c', 'e', 'd'])
+ a | b
+ a & b
+ a.difference(b)
+
+Also available is the ``sym_diff (^)`` operation, which returns elements
+that appear in either ``idx1`` or ``idx2`` but not both. This is
+equivalent to the Index created by ``idx1.difference(idx2).union(idx2.difference(idx1))``,
+with duplicates dropped.
+
+.. ipython:: python
+
+ idx1 = Index([1, 2, 3, 4])
+ idx2 = Index([2, 3, 4, 5])
+ idx1.sym_diff(idx2)
+ idx1 ^ idx2
+
Set / Reset Index
-----------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index be98f977bf2bf..8342c587ae4bb 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3752,7 +3752,7 @@ def append(self, other, ignore_index=False, verify_integrity=False):
'ignore_index=True')
index = None if other.name is None else [other.name]
- combined_columns = self.columns.tolist() + (self.columns | other.index).difference(self.columns).tolist()
+ combined_columns = self.columns.tolist() + self.columns.union(other.index).difference(self.columns).tolist()
other = other.reindex(combined_columns, copy=False)
other = DataFrame(other.values.reshape((1, len(other))),
index=index, columns=combined_columns).convert_objects()
| xref #8227
mixxing updates in indexing.rst
| https://api.github.com/repos/pandas-dev/pandas/pulls/8485 | 2014-10-06T14:28:12Z | 2014-10-06T15:01:11Z | 2014-10-06T15:01:11Z | 2014-10-06T16:50:42Z |
BUG: Bug in groupby .apply with a non-affecting mutation in the function (GH8467) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 6b2d2b6aad490..9b3f79836141b 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -946,7 +946,7 @@ Bug Fixes
- Bug in ``is_superperiod`` and ``is_subperiod`` cannot handle higher frequencies than ``S`` (:issue:`7760`, :issue:`7772`, :issue:`7803`)
- Bug in 32-bit platforms with ``Series.shift`` (:issue:`8129`)
- Bug in ``PeriodIndex.unique`` returns int64 ``np.ndarray`` (:issue:`7540`)
-
+- Bug in groupby ``.apply`` with a non-affecting mutation in the function (:issue:`8467`)
- Bug in ``DataFrame.reset_index`` which has ``MultiIndex`` contains ``PeriodIndex`` or ``DatetimeIndex`` with tz raises ``ValueError`` (:issue:`7746`, :issue:`7793`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 2e107e0b0e935..d63bc554c771a 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -2851,8 +2851,9 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
return concat(values)
if not all_indexed_same:
+ # GH 8467
return self._concat_objects(
- keys, values, not_indexed_same=not_indexed_same
+ keys, values, not_indexed_same=True,
)
try:
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 09763d53c017d..0e8b5d68e3fd7 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -2112,6 +2112,18 @@ def f_no_copy(x):
grpby_no_copy = mydf.groupby('cat1').apply(f_no_copy)
assert_series_equal(grpby_copy,grpby_no_copy)
+ def test_no_mutate_but_looks_like(self):
+
+ # GH 8467
+ # first show's mutation indicator
+ # second does not, but should yield the same results
+ df = DataFrame({'key': [1, 1, 1, 2, 2, 2, 3, 3, 3],
+ 'value': range(9)})
+
+ result1 = df.groupby('key', group_keys=True).apply(lambda x: x[:].key)
+ result2 = df.groupby('key', group_keys=True).apply(lambda x: x.key)
+ assert_series_equal(result1, result2)
+
def test_apply_chunk_view(self):
# Low level tinkering could be unsafe, make sure not
df = DataFrame({'key': [1, 1, 1, 2, 2, 2, 3, 3, 3],
| closes #8467
| https://api.github.com/repos/pandas-dev/pandas/pulls/8484 | 2014-10-06T13:19:58Z | 2014-10-06T13:54:52Z | 2014-10-06T13:54:51Z | 2014-10-06T13:54:52Z |
DEPR: deprecate value_range (GH8481) | diff --git a/doc/source/basics.rst b/doc/source/basics.rst
index 38828d5623536..bb65312f053f3 100644
--- a/doc/source/basics.rst
+++ b/doc/source/basics.rst
@@ -509,9 +509,6 @@ arguments. The special value ``all`` can also be used:
That feature relies on :ref:`select_dtypes <basics.selectdtypes>`. Refer to there for details about accepted inputs.
-There also is a utility function, ``value_range`` which takes a DataFrame and
-returns a series with the minimum/maximum values in the DataFrame.
-
.. _basics.idxmin:
Index of Min/Max Values
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 36379738b8d6a..9acb08cc16cab 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -772,6 +772,7 @@ Deprecations
``ambiguous`` to allow for more flexibility in dealing with DST transitions.
Replace ``infer_dst=True`` with ``ambiguous='infer'`` for the same behavior (:issue:`7943`).
See :ref:`the docs<timeseries.timezone_ambiguous>` for more details.
+- The top-level ``pd.value_range`` has been deprecated and can be replaced by ``.describe()`` (:issue:`8481`)
.. _whatsnew_0150.index_set_ops:
diff --git a/pandas/__init__.py b/pandas/__init__.py
index df5e6f567e3a6..69e8a4bad377e 100644
--- a/pandas/__init__.py
+++ b/pandas/__init__.py
@@ -53,11 +53,13 @@
from pandas.io.api import *
from pandas.computation.api import *
-from pandas.tools.describe import value_range
from pandas.tools.merge import merge, concat, ordered_merge
from pandas.tools.pivot import pivot_table, crosstab
from pandas.tools.plotting import scatter_matrix, plot_params
from pandas.tools.tile import cut, qcut
+from pandas.tools.util import value_range
from pandas.core.reshape import melt
from pandas.util.print_versions import show_versions
import pandas.util.testing
+
+
diff --git a/pandas/tools/describe.py b/pandas/tools/describe.py
deleted file mode 100644
index eca5a800b3c6c..0000000000000
--- a/pandas/tools/describe.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from pandas.core.series import Series
-
-
-def value_range(df):
- """
- Return the minimum and maximum of a dataframe in a series object
-
- Parameters
- ----------
- df : DataFrame
-
- Returns
- -------
- (maximum, minimum) : Series
-
- """
- return Series((min(df.min()), max(df.max())), ('Minimum', 'Maximum'))
diff --git a/pandas/tools/tests/test_tools.py b/pandas/tools/tests/test_tools.py
deleted file mode 100644
index 4fd70e28497a8..0000000000000
--- a/pandas/tools/tests/test_tools.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from pandas import DataFrame
-from pandas.tools.describe import value_range
-
-import numpy as np
-import pandas.util.testing as tm
-
-
-class TestTools(tm.TestCase):
-
- def test_value_range(self):
- df = DataFrame(np.random.randn(5, 5))
- df.ix[0, 2] = -5
- df.ix[2, 0] = 5
-
- res = value_range(df)
-
- self.assertEqual(res['Minimum'], -5)
- self.assertEqual(res['Maximum'], 5)
-
- df.ix[0, 1] = np.NaN
-
- self.assertEqual(res['Minimum'], -5)
- self.assertEqual(res['Maximum'], 5)
diff --git a/pandas/tools/util.py b/pandas/tools/util.py
index 215a76b84452a..72fdeaff36ef1 100644
--- a/pandas/tools/util.py
+++ b/pandas/tools/util.py
@@ -1,4 +1,5 @@
import operator
+import warnings
from pandas.compat import reduce
from pandas.core.index import Index
import numpy as np
@@ -47,3 +48,22 @@ def compose(*funcs):
"""Compose 2 or more callables"""
assert len(funcs) > 1, 'At least 2 callables must be passed to compose'
return reduce(_compose2, funcs)
+
+### FIXME: remove in 0.16
+def value_range(df):
+ """
+ Return the minimum and maximum of a dataframe in a series object
+
+ Parameters
+ ----------
+ df : DataFrame
+
+ Returns
+ -------
+ (maximum, minimum) : Series
+
+ """
+ from pandas import Series
+ warnings.warn("value_range is deprecated. Use .describe() instead", FutureWarning)
+
+ return Series((min(df.min()), max(df.max())), ('Minimum', 'Maximum'))
| closes #8481
| https://api.github.com/repos/pandas-dev/pandas/pulls/8483 | 2014-10-06T12:48:06Z | 2014-10-06T13:21:02Z | 2014-10-06T13:21:02Z | 2014-10-06T13:21:03Z |
BUG: sub-frame assignment of a multi-index frame breaks alignment | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 1b7b05847a901..b1ae1bd72a424 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -1048,3 +1048,4 @@ Bug Fixes
- Bug in ``NDFrame.loc`` indexing when row/column names were lost when target was a list/ndarray (:issue:`6552`)
- Regression in ``NDFrame.loc`` indexing when rows/columns were converted to Float64Index if target was an empty list/ndarray (:issue:`7774`)
- Bug in Series that allows it to be indexed by a DataFrame which has unexpected results. Such indexing is no longer permitted (:issue:`8444`)
+- Bug in item assignment of a DataFrame with multi-index columns where right-hand-side columns were not aligned (:issue:`7655`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 65f7d56f5aa8a..be98f977bf2bf 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2194,6 +2194,15 @@ def reindexer(value):
value = reindexer(value)
elif isinstance(value, DataFrame):
+ # align right-hand-side columns if self.columns
+ # is multi-index and self[key] is a sub-frame
+ if isinstance(self.columns, MultiIndex) and key in self.columns:
+ loc = self.columns.get_loc(key)
+ if isinstance(loc, (slice, Series, np.ndarray, Index)):
+ cols = _maybe_droplevels(self.columns[loc], key)
+ if len(cols) and not cols.equals(value.columns):
+ value = value.reindex_axis(cols, axis=1)
+ # now align rows
value = reindexer(value).T
elif isinstance(value, Categorical):
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 035a301807039..0dbca6f122b93 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -224,6 +224,31 @@ def test_setitem_list_of_tuples(self):
expected = Series(tuples, index=self.frame.index)
assert_series_equal(result, expected)
+ def test_setitem_mulit_index(self):
+ # GH7655, test that assigning to a sub-frame of a frame
+ # with multi-index columns aligns both rows and columns
+ it = ['jim', 'joe', 'jolie'], ['first', 'last'], \
+ ['left', 'center', 'right']
+
+ cols = MultiIndex.from_product(it)
+ index = pd.date_range('20141006',periods=20)
+ vals = np.random.randint(1, 1000, (len(index), len(cols)))
+ df = pd.DataFrame(vals, columns=cols, index=index)
+
+ i, j = df.index.values.copy(), it[-1][:]
+
+ np.random.shuffle(i)
+ df['jim'] = df['jolie'].loc[i, ::-1]
+ assert_frame_equal(df['jim'], df['jolie'])
+
+ np.random.shuffle(j)
+ df[('joe', 'first')] = df[('jolie', 'last')].loc[i, j]
+ assert_frame_equal(df[('joe', 'first')], df[('jolie', 'last')])
+
+ np.random.shuffle(j)
+ df[('joe', 'last')] = df[('jolie', 'first')].loc[i, j]
+ assert_frame_equal(df[('joe', 'last')], df[('jolie', 'first')])
+
def test_getitem_boolean(self):
# boolean indexing
d = self.tsframe.index[10]
| closes https://github.com/pydata/pandas/issues/7655
```
>>> df
jim joe jolie
first last first last first last
left center right left center right left center right left center right left center right left center right
2000-01-03 0 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51
2000-01-04 1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52
2000-01-05 2 5 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53
>>> i, j = df.index.values.copy(), it[-1][:]
>>> np.random.shuffle(i)
>>> df['jim'] = df['jolie'].loc[i, ::-1]
>>> df.loc[:, ['jim', 'jolie']]
jim jolie
first last first last
left center right left center right left center right left center right
2000-01-03 36 39 42 45 48 51 36 39 42 45 48 51
2000-01-04 37 40 43 46 49 52 37 40 43 46 49 52
2000-01-05 38 41 44 47 50 53 38 41 44 47 50 53
>>> np.random.shuffle(j)
>>> df[('joe', 'first')] = df[('jolie', 'last')].loc[i, j]
>>> np.random.shuffle(j)
>>> df[('joe', 'last')] = df[('jolie', 'first')].loc[i, j]
>>> df.loc[:, ['joe', 'jolie']]
joe jolie
first last first last
left center right left center right left center right left center right
2000-01-03 45 48 51 36 39 42 36 39 42 45 48 51
2000-01-04 46 49 52 37 40 43 37 40 43 46 49 52
2000-01-05 47 50 53 38 41 44 38 41 44 47 50 53
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/8480 | 2014-10-06T03:31:45Z | 2014-10-06T13:03:02Z | 2014-10-06T13:03:02Z | 2014-10-07T00:36:25Z |
TST: Speedup some slow plotting tests | diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 566f8a133a2c2..b9b239246fa54 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -266,9 +266,9 @@ def _check_ticks_props(self, axes, xlabelsize=None, xrot=None,
for label in labels:
if xlabelsize is not None:
- self.assertAlmostEqual(label.get_fontsize(), xlabelsize)
+ assert_allclose(label.get_fontsize(), xlabelsize)
if xrot is not None:
- self.assertAlmostEqual(label.get_rotation(), xrot)
+ assert_allclose(label.get_rotation(), xrot)
if ylabelsize or yrot:
if isinstance(ax.yaxis.get_minor_formatter(), NullFormatter):
@@ -278,9 +278,9 @@ def _check_ticks_props(self, axes, xlabelsize=None, xrot=None,
for label in labels:
if ylabelsize is not None:
- self.assertAlmostEqual(label.get_fontsize(), ylabelsize)
+ assert_allclose(label.get_fontsize(), ylabelsize)
if yrot is not None:
- self.assertAlmostEqual(label.get_rotation(), yrot)
+ assert_allclose(label.get_rotation(), yrot)
def _check_ax_scales(self, axes, xaxis='linear', yaxis='linear'):
"""
@@ -444,13 +444,13 @@ def setUp(self):
mpl.rcdefaults()
self.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1')
- self.ts = tm.makeTimeSeries()
+ self.ts = tm.makeTimeSeries(20)
self.ts.name = 'ts'
self.series = tm.makeStringSeries()
self.series.name = 'series'
- self.iseries = tm.makePeriodSeries()
+ self.iseries = tm.makePeriodSeries(20)
self.iseries.name = 'iseries'
@slow
@@ -2151,16 +2151,15 @@ def test_hist_df_legacy(self):
_check_plot_works(self.hist_df.hist)
# make sure layout is handled
- df = DataFrame(randn(100, 3))
+ df = DataFrame(randn(10, 3))
axes = _check_plot_works(df.hist, grid=False)
self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
self.assertFalse(axes[1, 1].get_visible())
- df = DataFrame(randn(100, 1))
- _check_plot_works(df.hist)
+ _check_plot_works(df[[0]].hist)
# make sure layout is handled
- df = DataFrame(randn(100, 6))
+ df = DataFrame(randn(10, 6))
axes = _check_plot_works(df.hist, layout=(4, 2))
self._check_axes_shape(axes, axes_num=6, layout=(4, 2))
@@ -2191,7 +2190,7 @@ def test_hist_df_legacy(self):
# make sure kwargs to hist are handled
ax = ser.hist(normed=True, cumulative=True, bins=4)
# height of last bin (index 5) must be 1.0
- self.assertAlmostEqual(ax.get_children()[5].get_height(), 1.0)
+ assert_allclose(ax.get_children()[5].get_height(), 1.0)
tm.close()
ax = ser.hist(log=True)
@@ -2240,7 +2239,7 @@ def test_hist_layout(self):
def test_scatter(self):
tm._skip_if_no_scipy()
- df = DataFrame(randn(100, 2))
+ df = DataFrame(randn(10, 2))
import pandas.tools.plotting as plt
def scat(**kwds):
@@ -2260,7 +2259,7 @@ def scat2(x, y, by=None, ax=None, figsize=None):
return plt.scatter_plot(df, x, y, by, ax, figsize=None)
_check_plot_works(scat2, 0, 1)
- grouper = Series(np.repeat([1, 2, 3, 4, 5], 20), df.index)
+ grouper = Series(np.repeat([1, 2], 5), df.index)
_check_plot_works(scat2, 0, 1, by=grouper)
@slow
@@ -3130,10 +3129,10 @@ def test_grouped_box_return_type(self):
result = df.groupby('gender').boxplot()
self._check_box_return_type(result, 'dict', expected_keys=['Male', 'Female'])
- columns2 = 'X B C D A G Y N Q O'.split()
- df2 = DataFrame(random.randn(50, 10), columns=columns2)
- categories2 = 'A B C D E F G H I J'.split()
- df2['category'] = categories2 * 5
+ columns2 = 'X B'.split()
+ df2 = DataFrame(random.randn(4, 2), columns=columns2)
+ categories2 = 'A B'.split()
+ df2['category'] = categories2 * 2
for t in ['dict', 'axes', 'both']:
returned = df.groupby('classroom').boxplot(return_type=t)
diff --git a/pandas/tseries/tests/test_plotting.py b/pandas/tseries/tests/test_plotting.py
index 4a60cdbedae4d..4371782490964 100644
--- a/pandas/tseries/tests/test_plotting.py
+++ b/pandas/tseries/tests/test_plotting.py
@@ -51,15 +51,14 @@ def test_ts_plot_with_tz(self):
@slow
def test_frame_inferred(self):
# inferred freq
- import matplotlib.pyplot as plt
- idx = date_range('1/1/1987', freq='MS', periods=100)
+ idx = date_range('1/1/1987', freq='MS', periods=10)
idx = DatetimeIndex(idx.values, freq=None)
df = DataFrame(np.random.randn(len(idx), 3), index=idx)
_check_plot_works(df.plot)
# axes freq
- idx = idx[0:40].union(idx[45:99])
+ idx = idx[0:4].union(idx[6:])
df2 = DataFrame(np.random.randn(len(idx), 3), index=idx)
_check_plot_works(df2.plot)
@@ -113,7 +112,7 @@ def test_both_style_and_color(self):
def test_high_freq(self):
freaks = ['ms', 'us']
for freq in freaks:
- rng = date_range('1/1/2012', periods=100000, freq=freq)
+ rng = date_range('1/1/2012', periods=100, freq=freq)
ser = Series(np.random.randn(len(rng)), rng)
_check_plot_works(ser.plot)
| Chipping away at https://github.com/pydata/pandas/issues/8450
Unfortunately I wasn't able to find too much. Most of those tests are slow because they're checking a lot of things.
This will only shave about 30s off the test time. It's a start...
| https://api.github.com/repos/pandas-dev/pandas/pulls/8479 | 2014-10-06T02:31:53Z | 2015-05-09T16:00:59Z | null | 2022-10-13T00:16:10Z |
DOC: Some more vis cleanups | diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst
index 3285efadf8ad1..ec73a16ba5d00 100644
--- a/doc/source/visualization.rst
+++ b/doc/source/visualization.rst
@@ -13,7 +13,11 @@
np.set_printoptions(precision=4, suppress=True)
import matplotlib.pyplot as plt
plt.close('all')
- options.display.mpl_style = 'default'
+ import matplotlib
+ try:
+ matplotlib.style.use('ggplot')
+ except AttributeError:
+ options.display.mpl_style = 'default'
options.display.max_rows = 15
from pandas.compat import lrange
@@ -29,14 +33,11 @@ We use the standard convention for referencing the matplotlib API:
.. versionadded:: 0.11.0
-The ``display.mpl_style`` produces more appealing plots.
+The plots in this document are made using matplotlib's ``ggplot`` style (new in version 1.4).
+If your version of matplotlib is 1.3 or lower, setting the ``display.mpl_style`` to ``'default'``
+with ``pd.options.display.mpl_style = 'default'``
+to produce more appealing plots.
When set, matplotlib's ``rcParams`` are changed (globally!) to nicer-looking settings.
-All the plots in the documentation are rendered with this option set to the
-'default' style.
-
-.. ipython:: python
-
- pd.options.display.mpl_style = 'default'
We provide the basics in pandas to easily create decent looking plots.
See the :ref:`ecosystem <ecosystem.visualization>` section for visualization
@@ -77,6 +78,7 @@ On DataFrame, :meth:`~DataFrame.plot` is a convenience to plot all of the column
.. ipython:: python
:suppress:
+ plt.close('all')
np.random.seed(123456)
.. ipython:: python
@@ -93,6 +95,7 @@ You can plot one column versus another using the `x` and `y` keywords in
.. ipython:: python
:suppress:
+ plt.close('all')
plt.figure()
np.random.seed(123456)
@@ -169,6 +172,7 @@ bar plot:
.. ipython:: python
:suppress:
+ plt.close('all')
plt.figure()
np.random.seed(123456)
@@ -184,6 +188,7 @@ To produce a stacked bar plot, pass ``stacked=True``:
.. ipython:: python
:suppress:
+ plt.close('all')
plt.figure()
.. ipython:: python
@@ -196,6 +201,7 @@ To get horizontal bar plots, pass ``kind='barh'``:
.. ipython:: python
:suppress:
+ plt.close('all')
plt.figure()
.. ipython:: python
@@ -222,6 +228,12 @@ Histogram can be drawn specifying ``kind='hist'``.
@savefig hist_new.png
df4.plot(kind='hist', alpha=0.5)
+
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Histogram can be stacked by ``stacked=True``. Bin size can be changed by ``bins`` keyword.
.. ipython:: python
@@ -231,6 +243,11 @@ Histogram can be stacked by ``stacked=True``. Bin size can be changed by ``bins`
@savefig hist_new_stacked.png
df4.plot(kind='hist', stacked=True, bins=20)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
You can pass other keywords supported by matplotlib ``hist``. For example, horizontal and cumulative histgram can be drawn by ``orientation='horizontal'`` and ``cumulative='True'``.
.. ipython:: python
@@ -240,6 +257,10 @@ You can pass other keywords supported by matplotlib ``hist``. For example, horiz
@savefig hist_new_kwargs.png
df4['a'].plot(kind='hist', orientation='horizontal', cumulative=True)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
See the :meth:`hist <matplotlib.axes.Axes.hist>` method and the
`matplotlib hist documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist>`__ for more.
@@ -254,6 +275,10 @@ The existing interface ``DataFrame.hist`` to plot histogram still can be used.
@savefig hist_plot_ex.png
df['A'].diff().hist()
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
:meth:`DataFrame.hist` plots the histograms of the columns on multiple
subplots:
@@ -273,6 +298,7 @@ The ``by`` keyword can be specified to plot grouped histograms:
.. ipython:: python
:suppress:
+ plt.close('all')
plt.figure()
np.random.seed(123456)
@@ -302,6 +328,7 @@ a uniform random variable on [0,1).
.. ipython:: python
:suppress:
+ plt.close('all')
np.random.seed(123456)
.. ipython:: python
@@ -332,6 +359,11 @@ more complicated colorization, you can get each drawn artists by passing
@savefig box_new_colorize.png
df.plot(kind='box', color=color, sym='r+')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Also, you can pass other keywords supported by matplotlib ``boxplot``.
For example, horizontal and custom-positioned boxplot can be drawn by
``vert=False`` and ``positions`` keywords.
@@ -351,6 +383,7 @@ The existing interface ``DataFrame.boxplot`` to plot boxplot still can be used.
.. ipython:: python
:suppress:
+ plt.close('all')
np.random.seed(123456)
.. ipython:: python
@@ -368,6 +401,7 @@ groupings. For instance,
.. ipython:: python
:suppress:
+ plt.close('all')
np.random.seed(123456)
.. ipython:: python
@@ -387,6 +421,7 @@ columns:
.. ipython:: python
:suppress:
+ plt.close('all')
np.random.seed(123456)
.. ipython:: python
@@ -442,6 +477,11 @@ DataFrame.
@savefig boxplot_groupby.png
bp = df_box.boxplot(by='g')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Compare to:
.. ipython:: python
@@ -450,6 +490,11 @@ Compare to:
@savefig groupby_boxplot_vis.png
bp = df_box.groupby('g').boxplot()
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
.. _visualization.area_plot:
Area Plot
@@ -479,6 +524,7 @@ To produce an unstacked plot, pass ``stacked=False``. Alpha value is set to 0.5
.. ipython:: python
:suppress:
+ plt.close('all')
plt.figure()
.. ipython:: python
@@ -501,6 +547,7 @@ These can be specified by ``x`` and ``y`` keywords each.
:suppress:
np.random.seed(123456)
+ plt.close('all')
plt.figure()
.. ipython:: python
@@ -521,6 +568,11 @@ It is recommended to specify ``color`` and ``label`` keywords to distinguish eac
df.plot(kind='scatter', x='c', y='d',
color='DarkGreen', label='Group 2', ax=ax);
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
The keyword ``c`` may be given as the name of a column to provide colors for
each point:
@@ -529,6 +581,12 @@ each point:
@savefig scatter_plot_colored.png
df.plot(kind='scatter', x='a', y='b', c='c', s=50);
+
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
You can pass other keywords supported by matplotlib ``scatter``.
Below example shows a bubble chart using a dataframe column values as bubble size.
@@ -537,6 +595,11 @@ Below example shows a bubble chart using a dataframe column values as bubble siz
@savefig scatter_plot_bubble.png
df.plot(kind='scatter', x='a', y='b', s=df['c']*200);
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
See the :meth:`scatter <matplotlib.axes.Axes.scatter>` method and the
`matplotlib scatter documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`__ for more.
@@ -582,6 +645,7 @@ given by column ``z``. The bins are aggregated with numpy's ``max`` function.
.. ipython:: python
:suppress:
+ plt.close('all')
plt.figure()
np.random.seed(123456)
@@ -595,6 +659,10 @@ given by column ``z``. The bins are aggregated with numpy's ``max`` function.
df.plot(kind='hexbin', x='a', y='b', C='z', reduce_C_function=np.max,
gridsize=25)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
See the :meth:`hexbin <matplotlib.axes.Axes.hexbin>` method and the
`matplotlib hexbin documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hexbin>`__ for more.
@@ -623,6 +691,11 @@ A ``ValueError`` will be raised if there are any negative values in your data.
@savefig series_pie_plot.png
series.plot(kind='pie', figsize=(6, 6))
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
For pie plots it's best to use square figures, one's with an equal aspect ratio. You can create the
figure with equal width and height, or force the aspect ratio to be equal after plotting by
calling ``ax.set_aspect('equal')`` on the returned ``axes`` object.
@@ -645,6 +718,11 @@ A legend will be drawn in each pie plots by default; specify ``legend=False`` to
@savefig df_pie_plot.png
df.plot(kind='pie', subplots=True, figsize=(8, 4))
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
You can use the ``labels`` and ``colors`` keywords to specify the labels and colors of each wedge.
.. warning::
@@ -673,6 +751,7 @@ If you pass values whose sum total is less than 1.0, matplotlib draws a semicirc
.. ipython:: python
:suppress:
+ plt.close('all')
plt.figure()
.. ipython:: python
@@ -758,6 +837,11 @@ You can create a scatter plot matrix using the
@savefig scatter_matrix_kde.png
scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
.. _visualization.kde:
Density Plot
@@ -781,6 +865,11 @@ setting ``kind='kde'``:
@savefig kde_plot.png
ser.plot(kind='kde')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
.. _visualization.andrews_curves:
Andrews Curves
@@ -829,6 +918,11 @@ represents one data point. Points that tend to cluster will appear closer togeth
@savefig parallel_coordinates.png
parallel_coordinates(data, 'Name')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
.. _visualization.lag:
Lag Plot
@@ -855,6 +949,11 @@ implies that the underlying data are not random.
@savefig lag_plot.png
lag_plot(data)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
.. _visualization.autocorrelation:
Autocorrelation Plot
@@ -885,6 +984,11 @@ confidence band.
@savefig autocorrelation_plot.png
autocorrelation_plot(data)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
.. _visualization.bootstrap:
Bootstrap Plot
@@ -945,6 +1049,11 @@ be colored differently.
@savefig radviz.png
radviz(data, 'Name')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
.. _visualization.formatting:
Plot Formatting
@@ -958,6 +1067,11 @@ layout and formatting of the returned plot:
@savefig series_plot_basic2.png
plt.figure(); ts.plot(style='k--', label='Series');
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
For each kind of plot (e.g. `line`, `bar`, `scatter`) any additional arguments
keywords are passed along to the corresponding matplotlib function
(:meth:`ax.plot() <matplotlib.axes.Axes.plot>`,
@@ -984,6 +1098,11 @@ shown by default.
@savefig frame_plot_basic_noleg.png
df.plot(legend=False)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Scales
~~~~~~
@@ -995,7 +1114,6 @@ You may pass ``logy`` to get a log-scale Y axis.
plt.figure()
np.random.seed(123456)
-
.. ipython:: python
ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000))
@@ -1004,6 +1122,11 @@ You may pass ``logy`` to get a log-scale Y axis.
@savefig series_plot_logy.png
ts.plot(logy=True)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
See also the ``logx`` and ``loglog`` keyword arguments.
Plotting on a Secondary Y-axis
@@ -1023,6 +1146,11 @@ To plot data on a secondary y-axis, use the ``secondary_y`` keyword:
@savefig series_plot_secondary_y.png
df.B.plot(secondary_y=True, style='g')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
To plot some columns in a DataFrame, give the column names to the ``secondary_y``
keyword:
@@ -1034,6 +1162,10 @@ keyword:
@savefig frame_plot_secondary_y.png
ax.right_ax.set_ylabel('AB scale')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
Note that the columns plotted on the secondary y-axis is automatically marked
with "(right)" in the legend. To turn off the automatic marking, use the
@@ -1046,6 +1178,10 @@ with "(right)" in the legend. To turn off the automatic marking, use the
@savefig frame_plot_secondary_y_no_right.png
df.plot(secondary_y=['A', 'B'], mark_right=False)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
Suppressing Tick Resolution Adjustment
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1064,6 +1200,10 @@ Here is the default behavior, notice how the x-axis tick labelling is performed:
@savefig ser_plot_suppress.png
df.A.plot()
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
Using the ``x_compat`` parameter, you can suppress this behavior:
@@ -1074,6 +1214,10 @@ Using the ``x_compat`` parameter, you can suppress this behavior:
@savefig ser_plot_suppress_parm.png
df.A.plot(x_compat=True)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
If you have more than one plot that needs to be suppressed, the ``use`` method
in ``pandas.plot_params`` can be used in a `with statement`:
@@ -1090,6 +1234,11 @@ in ``pandas.plot_params`` can be used in a `with statement`:
df.B.plot(color='g')
df.C.plot(color='b')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Subplots
~~~~~~~~
@@ -1101,6 +1250,11 @@ with the ``subplots`` keyword:
@savefig frame_plot_subplots.png
df.plot(subplots=True, figsize=(6, 6));
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Using Layout and Targetting Multiple Axes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1119,12 +1273,22 @@ or columns needed, given the other.
@savefig frame_plot_subplots_layout.png
df.plot(subplots=True, layout=(3, 2), figsize=(6, 6), sharex=False);
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
The above example is identical to using
.. ipython:: python
df.plot(subplots=True, layout=(3, -1), figsize=(6, 6), sharex=False);
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
The required number of columns (2) is inferred from the number of series to plot
and the given number of rows (3).
@@ -1138,7 +1302,7 @@ These must be configured when creating axes.
.. ipython:: python
fig, axes = plt.subplots(4, 4, figsize=(6, 6));
- plt.adjust_subplots(wspace=0.5, hspace=0.5);
+ plt.subplots_adjust(wspace=0.5, hspace=0.5);
target1 = [axes[0][0], axes[1][1], axes[2][2], axes[3][3]]
target2 = [axes[3][0], axes[2][1], axes[1][2], axes[0][3]]
@@ -1146,6 +1310,11 @@ These must be configured when creating axes.
@savefig frame_plot_subplots_multi_ax.png
(-df).plot(subplots=True, ax=target2, legend=False);
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Another option is passing an ``ax`` argument to :meth:`Series.plot` to plot on a particular axis:
.. ipython:: python
@@ -1158,6 +1327,11 @@ Another option is passing an ``ax`` argument to :meth:`Series.plot` to plot on a
df = DataFrame(randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
.. ipython:: python
fig, axes = plt.subplots(nrows=2, ncols=2)
@@ -1210,6 +1384,11 @@ Here is an example of one way to easily plot group means with standard deviation
@savefig errorbar_example.png
means.plot(yerr=errors, ax=ax, kind='bar')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
.. _visualization.table:
Plotting Tables
@@ -1233,6 +1412,11 @@ Plotting with matplotlib table is now supported in :meth:`DataFrame.plot` and :
@savefig line_plot_table_true.png
df.plot(table=True, ax=ax)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Also, you can pass different :class:`DataFrame` or :class:`Series` for ``table`` keyword. The data will be drawn as displayed in print method (not transposed automatically). If required, it should be transposed manually as below example.
.. ipython:: python
@@ -1242,6 +1426,10 @@ Also, you can pass different :class:`DataFrame` or :class:`Series` for ``table``
@savefig line_plot_table_data.png
df.plot(table=np.round(df.T, 2), ax=ax)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
Finally, there is a helper function ``pandas.tools.plotting.table`` to create a table from :class:`DataFrame` and :class:`Series`, and add it to an ``matplotlib.Axes``. This function can accept keywords which matplotlib table has.
@@ -1256,6 +1444,11 @@ Finally, there is a helper function ``pandas.tools.plotting.table`` to create a
@savefig line_plot_table_describe.png
df.plot(ax=ax, ylim=(0, 2), legend=None)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
**Note**: You can get table instances on the axes using ``axes.tables`` property for further decorations. See the `matplotlib table documenation <http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.table>`__ for more.
.. _visualization.colormaps:
@@ -1293,6 +1486,11 @@ To use the cubehelix colormap, we can simply pass ``'cubehelix'`` to ``colormap=
@savefig cubehelix.png
df.plot(colormap='cubehelix')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
or we can pass the colormap itself
.. ipython:: python
@@ -1304,6 +1502,11 @@ or we can pass the colormap itself
@savefig cubehelix_cm.png
df.plot(colormap=cm.cubehelix)
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Colormaps can also be used other plot types, like bar charts:
.. ipython:: python
@@ -1321,6 +1524,11 @@ Colormaps can also be used other plot types, like bar charts:
@savefig greens.png
dd.plot(kind='bar', colormap='Greens')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Parallel coordinates charts:
.. ipython:: python
@@ -1330,6 +1538,11 @@ Parallel coordinates charts:
@savefig parallel_gist_rainbow.png
parallel_coordinates(data, 'Name', colormap='gist_rainbow')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Andrews curves charts:
.. ipython:: python
@@ -1339,6 +1552,10 @@ Andrews curves charts:
@savefig andrews_curve_winter.png
andrews_curves(data, 'Name', colormap='winter')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
Plotting directly with matplotlib
---------------------------------
@@ -1443,6 +1660,11 @@ RPlot is a flexible API for producing Trellis plots. These plots allow you to ar
@savefig rplot1_tips.png
plot.render(plt.gcf())
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
In the example above, data from the tips data set is arranged by the attributes 'sex' and 'smoker'. Since both of those attributes can take on one of two values, the resulting grid has two columns and two rows. A histogram is displayed for each cell of the grid.
.. ipython:: python
@@ -1456,6 +1678,11 @@ In the example above, data from the tips data set is arranged by the attributes
@savefig rplot2_tips.png
plot.render(plt.gcf())
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Example above is the same as previous except the plot is set to kernel density estimation. This shows how easy it is to have different plots for the same Trellis structure.
.. ipython:: python
@@ -1470,6 +1697,11 @@ Example above is the same as previous except the plot is set to kernel density e
@savefig rplot3_tips.png
plot.render(plt.gcf())
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
The plot above shows that it is possible to have two or more plots for the same data displayed on the same Trellis grid cell.
.. ipython:: python
@@ -1484,6 +1716,11 @@ The plot above shows that it is possible to have two or more plots for the same
@savefig rplot4_tips.png
plot.render(plt.gcf())
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
Above is a similar plot but with 2D kernel density estimation plot superimposed.
.. ipython:: python
@@ -1497,6 +1734,11 @@ Above is a similar plot but with 2D kernel density estimation plot superimposed.
@savefig rplot5_tips.png
plot.render(plt.gcf())
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
It is possible to only use one attribute for grouping data. The example above only uses 'sex' attribute. If the second grouping attribute is not specified, the plots will be arranged in a column.
.. ipython:: python
@@ -1510,6 +1752,11 @@ It is possible to only use one attribute for grouping data. The example above on
@savefig rplot6_tips.png
plot.render(plt.gcf())
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
If the first grouping attribute is not specified the plots will be arranged in a row.
.. ipython:: python
@@ -1527,6 +1774,11 @@ If the first grouping attribute is not specified the plots will be arranged in a
@savefig rplot7_tips.png
plot.render(plt.gcf())
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
As shown above, scatter plots are also possible. Scatter plots allow you to map various data attributes to graphical properties of the plot. In the example above the colour and shape of the scatter plot graphical objects is mapped to 'day' and 'size' attributes respectively. You use scale objects to specify these mappings. The list of scale classes is given below with initialization arguments for quick reference.
| Two things included:
1. Try to use ggplot style. If not, fall back to the previous 'default'.
2. Fixes some warnings in the doc build (part of https://github.com/pydata/pandas/issues/8234). There are some remaining warnings that I didn't have a chance to track down. Will see if I can later.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8478 | 2014-10-06T02:28:33Z | 2014-10-06T22:28:57Z | 2014-10-06T22:28:57Z | 2017-04-05T02:06:01Z |
BUG: allow std to work with timedeltas (GH8471) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 1b7b05847a901..5fdf9341bcd0e 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -638,7 +638,7 @@ TimedeltaIndex/Scalar
We introduce a new scalar type ``Timedelta``, which is a subclass of ``datetime.timedelta``, and behaves in a similar manner,
but allows compatibility with ``np.timedelta64`` types as well as a host of custom representation, parsing, and attributes.
This type is very similar to how ``Timestamp`` works for ``datetimes``. It is a nice-API box for the type. See the :ref:`docs <timedeltas.timedeltas>`.
-(:issue:`3009`, :issue:`4533`, :issue:`8209`, :issue:`8187`, :issue:`8190`, :issue:`7869`, :issue:`7661`, :issue:`8345`)
+(:issue:`3009`, :issue:`4533`, :issue:`8209`, :issue:`8187`, :issue:`8190`, :issue:`7869`, :issue:`7661`, :issue:`8345`, :issue:`8471`)
.. warning::
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index ffedeb9ade355..89736c27bf312 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3950,60 +3950,42 @@ def mad(self, axis=None, skipna=None, level=None, **kwargs):
return np.abs(demeaned).mean(axis=axis, skipna=skipna)
cls.mad = mad
- @Substitution(outname='variance',
- desc="Return unbiased variance over requested "
- "axis.\n\nNormalized by N-1 by default. "
- "This can be changed using the ddof argument")
- @Appender(_num_doc)
- def var(self, axis=None, skipna=None, level=None, ddof=1, **kwargs):
- if skipna is None:
- skipna = True
- if axis is None:
- axis = self._stat_axis_number
- if level is not None:
- return self._agg_by_level('var', axis=axis, level=level,
- skipna=skipna, ddof=ddof)
+ def _make_stat_function_ddof(name, desc, f):
- return self._reduce(nanops.nanvar, axis=axis, skipna=skipna,
- ddof=ddof)
- cls.var = var
-
- @Substitution(outname='stdev',
- desc="Return unbiased standard deviation over requested "
- "axis.\n\nNormalized by N-1 by default. "
- "This can be changed using the ddof argument")
- @Appender(_num_doc)
- def std(self, axis=None, skipna=None, level=None, ddof=1, **kwargs):
- if skipna is None:
- skipna = True
- if axis is None:
- axis = self._stat_axis_number
- if level is not None:
- return self._agg_by_level('std', axis=axis, level=level,
- skipna=skipna, ddof=ddof)
- result = self.var(axis=axis, skipna=skipna, ddof=ddof)
- if getattr(result, 'ndim', 0) > 0:
- return result.apply(np.sqrt)
- return np.sqrt(result)
- cls.std = std
-
- @Substitution(outname='standarderror',
- desc="Return unbiased standard error of the mean over "
- "requested axis.\n\nNormalized by N-1 by default. "
- "This can be changed using the ddof argument")
- @Appender(_num_doc)
- def sem(self, axis=None, skipna=None, level=None, ddof=1, **kwargs):
- if skipna is None:
- skipna = True
- if axis is None:
- axis = self._stat_axis_number
- if level is not None:
- return self._agg_by_level('sem', axis=axis, level=level,
- skipna=skipna, ddof=ddof)
+ @Substitution(outname=name, desc=desc)
+ @Appender(_num_doc)
+ def stat_func(self, axis=None, skipna=None, level=None, ddof=1,
+ **kwargs):
+ if skipna is None:
+ skipna = True
+ if axis is None:
+ axis = self._stat_axis_number
+ if level is not None:
+ return self._agg_by_level(name, axis=axis, level=level,
+ skipna=skipna, ddof=ddof)
+ return self._reduce(f, axis=axis,
+ skipna=skipna, ddof=ddof)
+ stat_func.__name__ = name
+ return stat_func
- return self._reduce(nanops.nansem, axis=axis, skipna=skipna,
- ddof=ddof)
- cls.sem = sem
+ cls.sem = _make_stat_function_ddof(
+ 'sem',
+ "Return unbiased standard error of the mean over "
+ "requested axis.\n\nNormalized by N-1 by default. "
+ "This can be changed using the ddof argument",
+ nanops.nansem)
+ cls.var = _make_stat_function_ddof(
+ 'var',
+ "Return unbiased variance over requested "
+ "axis.\n\nNormalized by N-1 by default. "
+ "This can be changed using the ddof argument",
+ nanops.nanvar)
+ cls.std = _make_stat_function_ddof(
+ 'std',
+ "Return unbiased standard deviation over requested "
+ "axis.\n\nNormalized by N-1 by default. "
+ "This can be changed using the ddof argument",
+ nanops.nanstd)
@Substitution(outname='compounded',
desc="Return the compound percentage of the values for "
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 3d6fa915d6b99..9703dba40a18a 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -228,7 +228,7 @@ def _wrap_results(result, dtype):
if not isinstance(result, np.ndarray):
result = lib.Timedelta(result)
else:
- result = result.view(dtype)
+ result = result.astype('i8').view(dtype)
return result
@@ -295,7 +295,7 @@ def get_median(x):
if values.ndim > 1:
# there's a non-empty array to apply over otherwise numpy raises
if notempty:
- return np.apply_along_axis(get_median, axis, values)
+ return _wrap_results(np.apply_along_axis(get_median, axis, values), dtype)
# must return the correct shape, but median is not defined for the
# empty set so return nans of shape "everything but the passed axis"
@@ -305,7 +305,7 @@ def get_median(x):
dims = np.arange(values.ndim)
ret = np.empty(shp[dims != axis])
ret.fill(np.nan)
- return ret
+ return _wrap_results(ret, dtype)
# otherwise return a scalar value
return _wrap_results(get_median(values) if notempty else np.nan, dtype)
@@ -329,15 +329,8 @@ def _get_counts_nanvar(mask, axis, ddof):
return count, d
-@disallow('M8','m8')
-@bottleneck_switch(ddof=1)
-def nanvar(values, axis=None, skipna=True, ddof=1):
-
- # we are going to allow timedelta64[ns] here
- # but NOT going to coerce them to the Timedelta type
- # as this could cause overflow
- # so var cannot be computed (but std can!)
-
+def _nanvar(values, axis=None, skipna=True, ddof=1):
+ # private nanvar calculator
mask = isnull(values)
if not _is_floating_dtype(values):
values = values.astype('f8')
@@ -352,6 +345,23 @@ def nanvar(values, axis=None, skipna=True, ddof=1):
XX = _ensure_numeric((values ** 2).sum(axis))
return np.fabs((XX - X ** 2 / count) / d)
+@disallow('M8')
+@bottleneck_switch(ddof=1)
+def nanstd(values, axis=None, skipna=True, ddof=1):
+
+ result = np.sqrt(_nanvar(values, axis=axis, skipna=skipna, ddof=ddof))
+ return _wrap_results(result, values.dtype)
+
+@disallow('M8','m8')
+@bottleneck_switch(ddof=1)
+def nanvar(values, axis=None, skipna=True, ddof=1):
+
+ # we are going to allow timedelta64[ns] here
+ # but NOT going to coerce them to the Timedelta type
+ # as this could cause overflow
+ # so var cannot be computed (but std can!)
+ return _nanvar(values, axis=axis, skipna=skipna, ddof=ddof)
+
@disallow('M8','m8')
def nansem(values, axis=None, skipna=True, ddof=1):
var = nanvar(values, axis, skipna, ddof=ddof)
@@ -517,7 +527,7 @@ def nankurt(values, axis=None, skipna=True):
return result
-@disallow('M8')
+@disallow('M8','m8')
def nanprod(values, axis=None, skipna=True):
mask = isnull(values)
if skipna and not _is_any_int_dtype(values):
diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py
index 509ef4925bb66..3ec00fee1d151 100644
--- a/pandas/tests/test_nanops.py
+++ b/pandas/tests/test_nanops.py
@@ -332,6 +332,10 @@ def test_nanvar(self):
self.check_funs_ddof(nanops.nanvar, np.var,
allow_complex=False, allow_date=False, allow_tdelta=False)
+ def test_nanstd(self):
+ self.check_funs_ddof(nanops.nanstd, np.std,
+ allow_complex=False, allow_date=False, allow_tdelta=True)
+
def test_nansem(self):
tm.skip_if_no_package('scipy.stats')
self.check_funs_ddof(nanops.nansem, np.var,
diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py
index 3d87751c296f3..282301499dcbc 100644
--- a/pandas/tseries/tests/test_timedeltas.py
+++ b/pandas/tseries/tests/test_timedeltas.py
@@ -479,6 +479,9 @@ def test_timedelta_ops(self):
expected = to_timedelta(timedelta(seconds=9))
self.assertEqual(result, expected)
+ result = td.to_frame().mean()
+ self.assertEqual(result[0], expected)
+
result = td.quantile(.1)
expected = Timedelta(np.timedelta64(2600,'ms'))
self.assertEqual(result, expected)
@@ -487,18 +490,28 @@ def test_timedelta_ops(self):
expected = to_timedelta('00:00:08')
self.assertEqual(result, expected)
+ result = td.to_frame().median()
+ self.assertEqual(result[0], expected)
+
# GH 6462
# consistency in returned values for sum
result = td.sum()
expected = to_timedelta('00:01:21')
self.assertEqual(result, expected)
- # you can technically do a std, but var overflows
- # so this is tricky
- self.assertRaises(TypeError, lambda : td.std())
+ result = td.to_frame().sum()
+ self.assertEqual(result[0], expected)
+
+ # std
+ result = td.std()
+ expected = to_timedelta(Series(td.dropna().values).std())
+ self.assertEqual(result, expected)
+
+ result = td.to_frame().std()
+ self.assertEqual(result[0], expected)
# invalid ops
- for op in ['skew','kurt','sem','var']:
+ for op in ['skew','kurt','sem','var','prod']:
self.assertRaises(TypeError, lambda : getattr(td,op)())
def test_timedelta_ops_scalar(self):
| close #8471
| https://api.github.com/repos/pandas-dev/pandas/pulls/8476 | 2014-10-05T22:14:34Z | 2014-10-05T23:52:47Z | 2014-10-05T23:52:47Z | 2014-10-05T23:52:47Z |
BUG: .at indexing should allow enlargement scalars w/o regards to the type of index (GH8473) | diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 8a77cc85efced..6d002bc8d633a 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1484,7 +1484,7 @@ class _ScalarAccessIndexer(_NDFrameIndexer):
""" access scalars quickly """
- def _convert_key(self, key):
+ def _convert_key(self, key, is_setter=False):
return list(key)
def __getitem__(self, key):
@@ -1505,7 +1505,7 @@ def __setitem__(self, key, value):
if len(key) != self.obj.ndim:
raise ValueError('Not enough indexers for scalar access '
'(setting)!')
- key = list(self._convert_key(key))
+ key = list(self._convert_key(key, is_setter=True))
key.append(value)
self.obj.set_value(*key, takeable=self._takeable)
@@ -1515,8 +1515,13 @@ class _AtIndexer(_ScalarAccessIndexer):
""" label based scalar accessor """
_takeable = False
- def _convert_key(self, key):
+ def _convert_key(self, key, is_setter=False):
""" require they keys to be the same type as the index (so we don't fallback) """
+
+ # allow arbitrary setting
+ if is_setter:
+ return list(key)
+
for ax, i in zip(self.obj.axes, key):
if ax.is_integer():
if not com.is_integer(i):
@@ -1536,7 +1541,7 @@ class _iAtIndexer(_ScalarAccessIndexer):
def _has_valid_setitem_indexer(self, indexer):
self._has_valid_positional_setitem_indexer(indexer)
- def _convert_key(self, key):
+ def _convert_key(self, key, is_setter=False):
""" require integer args (and convert to label arguments) """
for a, i in zip(self.obj.axes, key):
if not com.is_integer(i):
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 79e4b89889916..4eb06db57b054 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -2932,6 +2932,26 @@ def f():
p.loc[:,:,'C'] = Series([30,32],index=p_orig.items)
assert_panel_equal(p,expected)
+ # GH 8473
+ dates = date_range('1/1/2000', periods=8)
+ df_orig = DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
+
+ expected = pd.concat([df_orig,DataFrame({'A' : 7},index=[dates[-1]+1])])
+ df = df_orig.copy()
+ df.loc[dates[-1]+1, 'A'] = 7
+ assert_frame_equal(df,expected)
+ df = df_orig.copy()
+ df.at[dates[-1]+1, 'A'] = 7
+ assert_frame_equal(df,expected)
+
+ expected = pd.concat([df_orig,DataFrame({0 : 7},index=[dates[-1]+1])],axis=1)
+ df = df_orig.copy()
+ df.loc[dates[-1]+1, 0] = 7
+ assert_frame_equal(df,expected)
+ df = df_orig.copy()
+ df.at[dates[-1]+1, 0] = 7
+ assert_frame_equal(df,expected)
+
def test_partial_setting_mixed_dtype(self):
# in a mixed dtype environment, try to preserve dtypes
| closes #8473
| https://api.github.com/repos/pandas-dev/pandas/pulls/8475 | 2014-10-05T20:42:22Z | 2014-10-05T21:15:45Z | 2014-10-05T21:15:45Z | 2014-10-05T21:15:45Z |
TEST: add for sqlite fallback raising on datetime.time (and not failing silently) GH8341 | diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py
index 217114a00e980..8c29b26f80d01 100644
--- a/pandas/io/tests/test_sql.py
+++ b/pandas/io/tests/test_sql.py
@@ -1398,8 +1398,12 @@ def test_datetime_date(self):
def test_datetime_time(self):
# test support for datetime.time
- raise nose.SkipTest("datetime.time not supported for sqlite fallback")
-
+ df = DataFrame([time(9, 0, 0), time(9, 1, 30)], columns=["a"])
+ # test it raises an error and not fails silently (GH8341)
+ if self.flavor == 'sqlite':
+ self.assertRaises(sqlite3.InterfaceError, sql.to_sql, df,
+ 'test_time', self.conn)
+
def _get_index_columns(self, tbl_name):
ixs = sql.read_sql_query(
"SELECT * FROM sqlite_master WHERE type = 'index' " +
| Forgot to add this to #8470
| https://api.github.com/repos/pandas-dev/pandas/pulls/8474 | 2014-10-05T20:04:32Z | 2014-10-05T21:24:57Z | 2014-10-05T21:24:57Z | 2014-10-05T21:24:57Z |
Disallow Series indexing by DataFrame | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index f163efe45dd86..f71c1f1dfcbf1 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -1026,3 +1026,4 @@ Bug Fixes
- Bug in assignment with indexer where type diversity would break alignment (:issue:`8258`)
- Bug in ``NDFrame.loc`` indexing when row/column names were lost when target was a list/ndarray (:issue:`6552`)
- Regression in ``NDFrame.loc`` indexing when rows/columns were converted to Float64Index if target was an empty list/ndarray (:issue:`7774`)
+- Bug in Series that allows it to be indexed by a DataFrame which has unexpected results. Such indexing is no longer permitted (:issue:`8444`)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 24cfe9c54b3d9..f313352ef9660 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -21,7 +21,7 @@
_possibly_convert_platform, _try_sort,
ABCSparseArray, _maybe_match_name, _coerce_to_dtype,
_ensure_object, SettingWithCopyError,
- _maybe_box_datetimelike)
+ _maybe_box_datetimelike, ABCDataFrame)
from pandas.core.index import (Index, MultiIndex, InvalidIndexError,
_ensure_index)
from pandas.core.indexing import _check_bool_indexer, _maybe_convert_indices
@@ -545,6 +545,9 @@ def _get_with(self, key):
if isinstance(key, slice):
indexer = self.index._convert_slice_indexer(key, typ='getitem')
return self._get_values(indexer)
+ elif isinstance(key, ABCDataFrame):
+ raise TypeError('Indexing a Series with DataFrame is not supported, '\
+ 'use the appropriate DataFrame column')
else:
if isinstance(key, tuple):
try:
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index a8599bcda8513..521eddbba2e09 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -1222,6 +1222,12 @@ def test_getitem_dups(self):
expected = Series([3,4],index=['C','C'],dtype=np.int64)
result = s['C']
assert_series_equal(result, expected)
+
+ def test_getitem_dataframe(self):
+ rng = list(range(10))
+ s = pd.Series(10, index=rng)
+ df = pd.DataFrame(rng, index=rng)
+ self.assertRaises(TypeError, s.__getitem__, df>5)
def test_setitem_ambiguous_keyerror(self):
s = Series(lrange(10), index=lrange(0, 20, 2))
| Fixes #8444. I don't like importing DataFrame, but this was most obvious way to do it.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8472 | 2014-10-05T15:18:16Z | 2014-10-05T17:03:01Z | 2014-10-05T17:03:01Z | 2014-10-05T17:03:44Z |
SQL/ERR: raise error when insert failed with sqlite fallback (GH8341) | diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 29ff08391e0e4..e6230f1e54800 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -1155,6 +1155,7 @@ def run_transaction(self):
self.con.commit()
except:
self.con.rollback()
+ raise
finally:
cur.close()
| Related to #8341, does not closes it, but deals with the fact that it now fails silently
| https://api.github.com/repos/pandas-dev/pandas/pulls/8470 | 2014-10-05T10:08:12Z | 2014-10-05T18:01:12Z | 2014-10-05T18:01:12Z | 2014-10-05T18:01:12Z |
Let PeriodIndex infer frequency by converting first element to Period | diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py
index b4d8a6547950d..6fde54a3eeb9b 100644
--- a/pandas/tseries/period.py
+++ b/pandas/tseries/period.py
@@ -683,6 +683,11 @@ def _from_arraylike(cls, data, freq, tz):
if freq is None and len(data) > 0:
freq = getattr(data[0], 'freq', None)
+ if freq is None:
+ try:
+ freq = getattr(Period(data[0]), 'freq', None)
+ except Exception:
+ pass
if freq is None:
raise ValueError('freq not specified and cannot be '
@@ -702,6 +707,11 @@ def _from_arraylike(cls, data, freq, tz):
else:
if freq is None and len(data) > 0:
freq = getattr(data[0], 'freq', None)
+ if freq is None:
+ try:
+ freq = getattr(Period(data[0]), 'freq', None)
+ except Exception:
+ pass
if freq is None:
raise ValueError('freq not specified and cannot be '
| Fix for #8466.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8468 | 2014-10-05T05:15:55Z | 2014-10-05T13:52:39Z | null | 2014-10-05T13:52:39Z |
CI: install version of miniconda corresponding to python version | diff --git a/ci/install_conda.sh b/ci/install_conda.sh
index ec0aa5fef84ae..00c2e66c5d0e5 100755
--- a/ci/install_conda.sh
+++ b/ci/install_conda.sh
@@ -67,7 +67,15 @@ fi
python_major_version="${TRAVIS_PYTHON_VERSION:0:1}"
[ "$python_major_version" == "2" ] && python_major_version=""
-wget http://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh -O miniconda.sh || exit 1
+function mc_version()
+{
+ wget -O - -o /dev/null http://repo.continuum.io/miniconda | \
+ egrep -o "\">Miniconda${python_major_version}.+Linux-x86_64.sh</" | \
+ egrep -o '\d+\.\d+\.\d+' | sort -V | tail -1
+}
+
+
+wget http://repo.continuum.io/miniconda/Miniconda${python_major_version}-$(mc_version)-Linux-x86_64.sh -O miniconda.sh || exit 1
bash miniconda.sh -b -p $HOME/miniconda || exit 1
conda config --set always_yes yes --set changeps1 no || exit 1
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/8465 | 2014-10-04T21:46:35Z | 2015-05-09T16:01:34Z | null | 2022-10-13T00:16:09Z |
BUG: fix Index.reindex to preserve type when target is empty list/ndarray | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 68f313f321fc8..f163efe45dd86 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -1025,3 +1025,4 @@ Bug Fixes
- Bug in NDFrame.equals gives false negatives with dtype=object (:issue:`8437`)
- Bug in assignment with indexer where type diversity would break alignment (:issue:`8258`)
- Bug in ``NDFrame.loc`` indexing when row/column names were lost when target was a list/ndarray (:issue:`6552`)
+- Regression in ``NDFrame.loc`` indexing when rows/columns were converted to Float64Index if target was an empty list/ndarray (:issue:`7774`)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index f2ff44bb5214c..ffedeb9ade355 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1707,15 +1707,11 @@ def _reindex_axes(self, axes, level, limit, method, fill_value, copy):
if labels is None:
continue
- # convert to an index if we are not a multi-selection
ax = self._get_axis(a)
- if level is None:
- labels = _ensure_index(labels)
-
- axis = self._get_axis_number(a)
new_index, indexer = ax.reindex(
labels, level=level, limit=limit, method=method)
+ axis = self._get_axis_number(a)
obj = obj._reindex_with_indexers(
{axis: [new_index, indexer]}, method=method,
fill_value=fill_value, limit=limit, copy=copy,
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 2048081573308..e10f4b2009817 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -1594,7 +1594,14 @@ def reindex(self, target, method=None, level=None, limit=None):
# (i.e. neither Index nor Series).
preserve_names = not hasattr(target, 'name')
- target = _ensure_index(target)
+ # GH7774: preserve dtype/tz if target is empty and not an Index.
+ target = _ensure_has_len(target) # target may be an iterator
+ if not isinstance(target, Index) and len(target) == 0:
+ attrs = self._get_attributes_dict()
+ attrs.pop('freq', None) # don't preserve freq
+ target = self._simple_new(np.empty(0, dtype=self.dtype), **attrs)
+ else:
+ target = _ensure_index(target)
if level is not None:
if method is not None:
raise TypeError('Fill method not supported if level passed')
@@ -3706,7 +3713,17 @@ def reindex(self, target, method=None, level=None, limit=None):
if level is not None:
if method is not None:
raise TypeError('Fill method not supported if level passed')
- target = _ensure_index(target)
+
+ # GH7774: preserve dtype/tz if target is empty and not an Index.
+ target = _ensure_has_len(target) # target may be an iterator
+ if len(target) == 0 and not isinstance(target, Index):
+ idx = self.levels[level]
+ attrs = idx._get_attributes_dict()
+ attrs.pop('freq', None) # don't preserve freq
+ target = type(idx)._simple_new(np.empty(0, dtype=idx.dtype),
+ **attrs)
+ else:
+ target = _ensure_index(target)
target, indexer, _ = self._join_level(target, level, how='right',
return_indexers=True)
else:
@@ -4566,3 +4583,13 @@ def _get_na_rep(dtype):
def _get_na_value(dtype):
return {np.datetime64: tslib.NaT, np.timedelta64: tslib.NaT}.get(dtype,
np.nan)
+
+
+def _ensure_has_len(seq):
+ """If seq is an iterator, put its values into a list."""
+ try:
+ len(seq)
+ except TypeError:
+ return list(seq)
+ else:
+ return seq
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index ec9193d67151b..53a5bd4ae5d49 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -1049,6 +1049,34 @@ def test_reindex_preserves_name_if_target_is_list_or_ndarray(self):
self.assertEqual(idx.reindex(dt_idx.values)[0].name, 'foobar')
self.assertEqual(idx.reindex(dt_idx.tolist())[0].name, 'foobar')
+ def test_reindex_preserves_type_if_target_is_empty_list_or_array(self):
+ # GH7774
+ idx = pd.Index(list('abc'))
+ def get_reindex_type(target):
+ return idx.reindex(target)[0].dtype.type
+
+ self.assertEqual(get_reindex_type([]), np.object_)
+ self.assertEqual(get_reindex_type(np.array([])), np.object_)
+ self.assertEqual(get_reindex_type(np.array([], dtype=np.int64)),
+ np.object_)
+
+ def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self):
+ # GH7774
+ idx = pd.Index(list('abc'))
+ def get_reindex_type(target):
+ return idx.reindex(target)[0].dtype.type
+
+ self.assertEqual(get_reindex_type(pd.Int64Index([])), np.int_)
+ self.assertEqual(get_reindex_type(pd.Float64Index([])), np.float_)
+ self.assertEqual(get_reindex_type(pd.DatetimeIndex([])), np.datetime64)
+
+ reindexed = idx.reindex(pd.MultiIndex([pd.Int64Index([]),
+ pd.Float64Index([])],
+ [[], []]))[0]
+ self.assertEqual(reindexed.levels[0].dtype.type, np.int64)
+ self.assertEqual(reindexed.levels[1].dtype.type, np.float64)
+
+
class Numeric(Base):
@@ -1699,6 +1727,13 @@ def test_roundtrip_pickle_with_tz(self):
unpickled = self.round_trip_pickle(index)
self.assertTrue(index.equals(unpickled))
+ def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self):
+ # GH7774
+ index = date_range('20130101', periods=3, tz='US/Eastern')
+ self.assertEqual(str(index.reindex([])[0].tz), 'US/Eastern')
+ self.assertEqual(str(index.reindex(np.array([]))[0].tz), 'US/Eastern')
+
+
class TestPeriodIndex(Base, tm.TestCase):
_holder = PeriodIndex
_multiprocess_can_split_ = True
@@ -3321,6 +3356,21 @@ def test_reindex_preserves_names_when_target_is_list_or_ndarray(self):
self.assertEqual(idx.reindex(other_dtype.tolist())[0].names, ['foo', 'bar'])
self.assertEqual(idx.reindex(other_dtype.values)[0].names, ['foo', 'bar'])
+ def test_reindex_lvl_preserves_names_when_target_is_list_or_array(self):
+ # GH7774
+ idx = pd.MultiIndex.from_product([[0, 1], ['a', 'b']],
+ names=['foo', 'bar'])
+ self.assertEqual(idx.reindex([], level=0)[0].names, ['foo', 'bar'])
+ self.assertEqual(idx.reindex([], level=1)[0].names, ['foo', 'bar'])
+
+ def test_reindex_lvl_preserves_type_if_target_is_empty_list_or_array(self):
+ # GH7774
+ idx = pd.MultiIndex.from_product([[0, 1], ['a', 'b']])
+ self.assertEqual(idx.reindex([], level=0)[0].levels[0].dtype.type,
+ np.int_)
+ self.assertEqual(idx.reindex([], level=1)[0].levels[1].dtype.type,
+ np.object_)
+
def test_get_combined_index():
from pandas.core.index import _get_combined_index
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 97ebca39aae5a..79e4b89889916 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -3832,23 +3832,41 @@ def test_set_ix_out_of_bounds_axis_1(self):
def test_iloc_empty_list_indexer_is_ok(self):
from pandas.util.testing import makeCustomDataframe as mkdf
df = mkdf(5, 2)
- assert_frame_equal(df.iloc[:,[]], df.iloc[:, :0]) # vertical empty
- assert_frame_equal(df.iloc[[],:], df.iloc[:0, :]) # horizontal empty
- assert_frame_equal(df.iloc[[]], df.iloc[:0, :]) # horizontal empty
+ # vertical empty
+ assert_frame_equal(df.iloc[:, []], df.iloc[:, :0],
+ check_index_type=True, check_column_type=True)
+ # horizontal empty
+ assert_frame_equal(df.iloc[[], :], df.iloc[:0, :],
+ check_index_type=True, check_column_type=True)
+ # horizontal empty
+ assert_frame_equal(df.iloc[[]], df.iloc[:0, :],
+ check_index_type=True, check_column_type=True)
def test_loc_empty_list_indexer_is_ok(self):
from pandas.util.testing import makeCustomDataframe as mkdf
df = mkdf(5, 2)
- assert_frame_equal(df.loc[:,[]], df.iloc[:, :0]) # vertical empty
- assert_frame_equal(df.loc[[],:], df.iloc[:0, :]) # horizontal empty
- assert_frame_equal(df.loc[[]], df.iloc[:0, :]) # horizontal empty
+ # vertical empty
+ assert_frame_equal(df.loc[:, []], df.iloc[:, :0],
+ check_index_type=True, check_column_type=True)
+ # horizontal empty
+ assert_frame_equal(df.loc[[], :], df.iloc[:0, :],
+ check_index_type=True, check_column_type=True)
+ # horizontal empty
+ assert_frame_equal(df.loc[[]], df.iloc[:0, :],
+ check_index_type=True, check_column_type=True)
def test_ix_empty_list_indexer_is_ok(self):
from pandas.util.testing import makeCustomDataframe as mkdf
df = mkdf(5, 2)
- assert_frame_equal(df.ix[:,[]], df.iloc[:, :0]) # vertical empty
- assert_frame_equal(df.ix[[],:], df.iloc[:0, :]) # horizontal empty
- assert_frame_equal(df.ix[[]], df.iloc[:0, :]) # horizontal empty
+ # vertical empty
+ assert_frame_equal(df.ix[:, []], df.iloc[:, :0],
+ check_index_type=True, check_column_type=True)
+ # horizontal empty
+ assert_frame_equal(df.ix[[], :], df.iloc[:0, :],
+ check_index_type=True, check_column_type=True)
+ # horizontal empty
+ assert_frame_equal(df.ix[[]], df.iloc[:0, :],
+ check_index_type=True, check_column_type=True)
def test_deprecate_float_indexers(self):
| This PR fixes #7774 and also includes:
TST: check index/columns types when doing empty loc/ix tests
CLN: don't _ensure_index in NDFrame._reindex_axes, it is done in Index.reindex
| https://api.github.com/repos/pandas-dev/pandas/pulls/8462 | 2014-10-04T17:18:39Z | 2014-10-05T14:05:18Z | 2014-10-05T14:05:18Z | 2014-10-05T19:03:13Z |
BUG: fix applymap to handle Timedelta | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index cba2d3c5aa0e9..2194e8c36a9e3 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3652,8 +3652,9 @@ def applymap(self, func):
# if we have a dtype == 'M8[ns]', provide boxed values
def infer(x):
- if com.is_datetime64_dtype(x):
- x = lib.map_infer(_values_from_object(x), lib.Timestamp)
+ if com.needs_i8_conversion(x):
+ f = com.i8_boxer(x)
+ x = lib.map_infer(_values_from_object(x), f)
return lib.map_infer(_values_from_object(x), func)
return self.apply(infer)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 700eb8591fdf9..cefeb89fbc41d 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -10117,6 +10117,13 @@ def test_applymap(self):
result = df.applymap(str)
assert_frame_equal(result,expected)
+ # datetime/timedelta
+ df['datetime'] = Timestamp('20130101')
+ df['timedelta'] = Timedelta('1 min')
+ result = df.applymap(str)
+ for f in ['datetime','timedelta']:
+ self.assertEquals(result.loc[0,f],str(df.loc[0,f]))
+
def test_filter(self):
# items
filtered = self.frame.filter(['A', 'B', 'E'])
| https://api.github.com/repos/pandas-dev/pandas/pulls/8461 | 2014-10-04T16:18:56Z | 2014-10-04T16:20:49Z | 2014-10-04T16:20:49Z | 2014-10-04T16:20:49Z | |
BUG: fix Index.reindex to preserve name when target is list/ndarray | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index e23f3ea6ff53a..1d9acadb68e58 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -1012,3 +1012,4 @@ Bug Fixes
- Bug in masked series assignment where mismatching types would break alignment (:issue:`8387`)
- Bug in NDFrame.equals gives false negatives with dtype=object (:issue:`8437`)
- Bug in assignment with indexer where type diversity would break alignment (:issue:`8258`)
+- Bug in ``NDFrame.loc`` indexing when row/column names were lost when target was a list/ndarray (:issue:`6552`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 2194e8c36a9e3..5cfb2affe5a7b 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2260,8 +2260,7 @@ def _reindex_axes(self, axes, level, limit, method, fill_value, copy):
def _reindex_index(self, new_index, method, copy, level, fill_value=NA,
limit=None):
new_index, indexer = self.index.reindex(new_index, method, level,
- limit=limit,
- copy_if_needed=True)
+ limit=limit)
return self._reindex_with_indexers({0: [new_index, indexer]},
copy=copy, fill_value=fill_value,
allow_dups=False)
@@ -2269,8 +2268,7 @@ def _reindex_index(self, new_index, method, copy, level, fill_value=NA,
def _reindex_columns(self, new_columns, copy, level, fill_value=NA,
limit=None):
new_columns, indexer = self.columns.reindex(new_columns, level=level,
- limit=limit,
- copy_if_needed=True)
+ limit=limit)
return self._reindex_with_indexers({1: [new_columns, indexer]},
copy=copy, fill_value=fill_value,
allow_dups=False)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 9f9b543f0fa7d..f2ff44bb5214c 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1776,8 +1776,8 @@ def reindex_axis(self, labels, axis=0, method=None, level=None, copy=True,
axis_name = self._get_axis_name(axis)
axis_values = self._get_axis(axis_name)
method = com._clean_fill_method(method)
- new_index, indexer = axis_values.reindex(
- labels, method, level, limit=limit, copy_if_needed=True)
+ new_index, indexer = axis_values.reindex(labels, method, level,
+ limit=limit)
return self._reindex_with_indexers(
{axis: [new_index, indexer]}, method=method, fill_value=fill_value,
limit=limit, copy=copy)
diff --git a/pandas/core/index.py b/pandas/core/index.py
index da8edf13ff18f..2048081573308 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -1578,17 +1578,22 @@ def _get_method(self, method):
}
return aliases.get(method, method)
- def reindex(self, target, method=None, level=None, limit=None,
- copy_if_needed=False):
+ def reindex(self, target, method=None, level=None, limit=None):
"""
- For Index, simply returns the new index and the results of
- get_indexer. Provided here to enable an interface that is amenable for
- subclasses of Index whose internals are different (like MultiIndex)
+ Create index with target's values (move/add/delete values as necessary)
Returns
-------
- (new_index, indexer, mask) : tuple
+ new_index : pd.Index
+ Resulting index
+ indexer : np.ndarray or None
+ Indices of output values in original index
+
"""
+ # GH6552: preserve names when reindexing to non-named target
+ # (i.e. neither Index nor Series).
+ preserve_names = not hasattr(target, 'name')
+
target = _ensure_index(target)
if level is not None:
if method is not None:
@@ -1596,16 +1601,8 @@ def reindex(self, target, method=None, level=None, limit=None,
_, indexer, _ = self._join_level(target, level, how='right',
return_indexers=True)
else:
-
if self.equals(target):
indexer = None
-
- # to avoid aliasing an existing index
- if (copy_if_needed and target.name != self.name and
- self.name is not None):
- if target.name is None:
- target = self.copy()
-
else:
if self.is_unique:
indexer = self.get_indexer(target, method=method,
@@ -1616,6 +1613,10 @@ def reindex(self, target, method=None, level=None, limit=None,
"with a method or limit")
indexer, missing = self.get_indexer_non_unique(target)
+ if preserve_names and target.nlevels == 1 and target.name != self.name:
+ target = target.copy()
+ target.name = self.name
+
return target, indexer
def join(self, other, how='left', level=None, return_indexers=False):
@@ -3686,17 +3687,21 @@ def get_indexer(self, target, method=None, limit=None):
return com._ensure_platform_int(indexer)
- def reindex(self, target, method=None, level=None, limit=None,
- copy_if_needed=False):
+ def reindex(self, target, method=None, level=None, limit=None):
"""
- Performs any necessary conversion on the input index and calls
- get_indexer. This method is here so MultiIndex and an Index of
- like-labeled tuples can play nice together
+ Create index with target's values (move/add/delete values as necessary)
Returns
-------
- (new_index, indexer, mask) : (MultiIndex, ndarray, ndarray)
+ new_index : pd.MultiIndex
+ Resulting index
+ indexer : np.ndarray or None
+ Indices of output values in original index
+
"""
+ # GH6552: preserve names when reindexing to non-named target
+ # (i.e. neither Index nor Series).
+ preserve_names = not hasattr(target, 'names')
if level is not None:
if method is not None:
@@ -3724,6 +3729,11 @@ def reindex(self, target, method=None, level=None, limit=None,
# hopefully?
target = MultiIndex.from_tuples(target)
+ if (preserve_names and target.nlevels == self.nlevels and
+ target.names != self.names):
+ target = target.copy(deep=False)
+ target.names = self.names
+
return target, indexer
@cache_readonly
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index a94e627952b75..c88d799a54fed 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -3088,7 +3088,7 @@ def reindex_axis(self, new_index, axis, method=None, limit=None,
"""
new_index = _ensure_index(new_index)
new_index, indexer = self.axes[axis].reindex(
- new_index, method=method, limit=limit, copy_if_needed=True)
+ new_index, method=method, limit=limit)
return self.reindex_indexer(new_index, indexer, axis=axis,
fill_value=fill_value, copy=copy)
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index c86797c7ac90c..ec9193d67151b 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -1019,6 +1019,36 @@ def test_nan_first_take_datetime(self):
exp = Index([idx[-1], idx[0], idx[1]])
tm.assert_index_equal(res, exp)
+ def test_reindex_preserves_name_if_target_is_list_or_ndarray(self):
+ # GH6552
+ idx = pd.Index([0, 1, 2])
+
+ dt_idx = pd.date_range('20130101', periods=3)
+
+ idx.name = None
+ self.assertEqual(idx.reindex([])[0].name, None)
+ self.assertEqual(idx.reindex(np.array([]))[0].name, None)
+ self.assertEqual(idx.reindex(idx.tolist())[0].name, None)
+ self.assertEqual(idx.reindex(idx.tolist()[:-1])[0].name, None)
+ self.assertEqual(idx.reindex(idx.values)[0].name, None)
+ self.assertEqual(idx.reindex(idx.values[:-1])[0].name, None)
+
+ # Must preserve name even if dtype changes.
+ self.assertEqual(idx.reindex(dt_idx.values)[0].name, None)
+ self.assertEqual(idx.reindex(dt_idx.tolist())[0].name, None)
+
+ idx.name = 'foobar'
+ self.assertEqual(idx.reindex([])[0].name, 'foobar')
+ self.assertEqual(idx.reindex(np.array([]))[0].name, 'foobar')
+ self.assertEqual(idx.reindex(idx.tolist())[0].name, 'foobar')
+ self.assertEqual(idx.reindex(idx.tolist()[:-1])[0].name, 'foobar')
+ self.assertEqual(idx.reindex(idx.values)[0].name, 'foobar')
+ self.assertEqual(idx.reindex(idx.values[:-1])[0].name, 'foobar')
+
+ # Must preserve name even if dtype changes.
+ self.assertEqual(idx.reindex(dt_idx.values)[0].name, 'foobar')
+ self.assertEqual(idx.reindex(dt_idx.tolist())[0].name, 'foobar')
+
class Numeric(Base):
@@ -3267,6 +3297,30 @@ def test_isin_level_kwarg(self):
self.assertRaises(KeyError, idx.isin, vals_1, level='C')
+ def test_reindex_preserves_names_when_target_is_list_or_ndarray(self):
+ # GH6552
+ idx = self.index.copy()
+ target = idx.copy()
+ idx.names = target.names = [None, None]
+
+ other_dtype = pd.MultiIndex.from_product([[1, 2], [3, 4]])
+
+ # list & ndarray cases
+ self.assertEqual(idx.reindex([])[0].names, [None, None])
+ self.assertEqual(idx.reindex(np.array([]))[0].names, [None, None])
+ self.assertEqual(idx.reindex(target.tolist())[0].names, [None, None])
+ self.assertEqual(idx.reindex(target.values)[0].names, [None, None])
+ self.assertEqual(idx.reindex(other_dtype.tolist())[0].names, [None, None])
+ self.assertEqual(idx.reindex(other_dtype.values)[0].names, [None, None])
+
+ idx.names = ['foo', 'bar']
+ self.assertEqual(idx.reindex([])[0].names, ['foo', 'bar'])
+ self.assertEqual(idx.reindex(np.array([]))[0].names, ['foo', 'bar'])
+ self.assertEqual(idx.reindex(target.tolist())[0].names, ['foo', 'bar'])
+ self.assertEqual(idx.reindex(target.values)[0].names, ['foo', 'bar'])
+ self.assertEqual(idx.reindex(other_dtype.tolist())[0].names, ['foo', 'bar'])
+ self.assertEqual(idx.reindex(other_dtype.values)[0].names, ['foo', 'bar'])
+
def test_get_combined_index():
from pandas.core.index import _get_combined_index
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 7213aaafd1376..97ebca39aae5a 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -3836,9 +3836,7 @@ def test_iloc_empty_list_indexer_is_ok(self):
assert_frame_equal(df.iloc[[],:], df.iloc[:0, :]) # horizontal empty
assert_frame_equal(df.iloc[[]], df.iloc[:0, :]) # horizontal empty
- # FIXME: fix loc & xs
def test_loc_empty_list_indexer_is_ok(self):
- raise nose.SkipTest('loc discards columns names')
from pandas.util.testing import makeCustomDataframe as mkdf
df = mkdf(5, 2)
assert_frame_equal(df.loc[:,[]], df.iloc[:, :0]) # vertical empty
@@ -3846,7 +3844,6 @@ def test_loc_empty_list_indexer_is_ok(self):
assert_frame_equal(df.loc[[]], df.iloc[:0, :]) # horizontal empty
def test_ix_empty_list_indexer_is_ok(self):
- raise nose.SkipTest('ix discards columns names')
from pandas.util.testing import makeCustomDataframe as mkdf
df = mkdf(5, 2)
assert_frame_equal(df.ix[:,[]], df.iloc[:, :0]) # vertical empty
| This PR fixes #6552 and also includes:
CLN: drop copy_if_needed kwarg of Index.reindex, it's True everywhere
TST: enable back empty-list loc/ix tests that failed before
DOC: Bump Index.reindex docstring
| https://api.github.com/repos/pandas-dev/pandas/pulls/8460 | 2014-10-04T14:18:29Z | 2014-10-04T20:02:08Z | 2014-10-04T20:02:08Z | 2014-11-02T21:33:35Z |
VIS: Cleanups in plotting.py | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 9d03b7b38bea7..8513fb7807084 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -257,6 +257,8 @@ API changes
- Added support for numpy 1.8+ data types (bool_, int_, float_, string_) for conversion to R dataframe (:issue:`8400`)
+- ``DataFrame.plot`` and ``Series.plot`` keywords are now have consistent orders (:issue:`8037`)
+
.. _whatsnew_0150.dt:
.dt accessor
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 1cc5e2a99148b..410494d3b0062 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -2784,6 +2784,9 @@ def test_pie_df(self):
ax = _check_plot_works(df.plot, kind='pie', y='Y')
self._check_text_labels(ax.texts, df.index)
+ ax = _check_plot_works(df.plot, kind='pie', y=2)
+ self._check_text_labels(ax.texts, df.index)
+
axes = _check_plot_works(df.plot, kind='pie', subplots=True)
self.assertEqual(len(axes), len(df.columns))
for ax in axes:
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 0b1a0ceb8da60..80db990a25ea7 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -852,16 +852,13 @@ def __init__(self, data, kind=None, by=None, subplots=False, sharex=True,
self._validate_color_args()
def _validate_color_args(self):
- from pandas import DataFrame
if 'color' not in self.kwds and 'colors' in self.kwds:
warnings.warn(("'colors' is being deprecated. Please use 'color'"
"instead of 'colors'"))
colors = self.kwds.pop('colors')
self.kwds['color'] = colors
- if ('color' in self.kwds and
- (isinstance(self.data, Series) or
- isinstance(self.data, DataFrame) and len(self.data.columns) == 1)):
+ if ('color' in self.kwds and self.nseries == 1):
# support series.plot(color='green')
self.kwds['color'] = [self.kwds['color']]
@@ -1264,7 +1261,6 @@ def _get_style(self, i, col_name):
return style or None
def _get_colors(self, num_colors=None, color_kwds='color'):
- from pandas.core.frame import DataFrame
if num_colors is None:
num_colors = self.nseries
@@ -1709,7 +1705,7 @@ def _get_plot_function(self):
raise ValueError("Log-y scales are not supported in area plot")
else:
f = MPLPlot._get_plot_function(self)
- def plotf(ax, x, y, style=None, column_num=0, **kwds):
+ def plotf(ax, x, y, style=None, column_num=None, **kwds):
if column_num == 0:
self._initialize_prior(len(self.data))
y_values = self._get_stacked_values(y, kwds['label'])
@@ -1764,8 +1760,8 @@ def __init__(self, data, **kwargs):
kwargs.setdefault('align', 'center')
self.tick_pos = np.arange(len(data))
- self.bottom = kwargs.pop('bottom', None)
- self.left = kwargs.pop('left', None)
+ self.bottom = kwargs.pop('bottom', 0)
+ self.left = kwargs.pop('left', 0)
self.log = kwargs.pop('log',False)
MPLPlot.__init__(self, data, **kwargs)
@@ -1796,13 +1792,11 @@ def _args_adjust(self):
def _get_plot_function(self):
if self.kind == 'bar':
def f(ax, x, y, w, start=None, **kwds):
- if self.bottom is not None:
- start = start + self.bottom
+ start = start + self.bottom
return ax.bar(x, y, w, bottom=start,log=self.log, **kwds)
elif self.kind == 'barh':
def f(ax, x, y, w, start=None, log=self.log, **kwds):
- if self.left is not None:
- start = start + self.left
+ start = start + self.left
return ax.barh(x, y, w, left=start, **kwds)
else:
raise NotImplementedError
@@ -2243,58 +2237,147 @@ def result(self):
'area': AreaPlot, 'pie': PiePlot}
-def plot_frame(frame=None, x=None, y=None, subplots=False, sharex=True,
- sharey=False, use_index=True, figsize=None, grid=None,
- legend=True, rot=None, ax=None, style=None, title=None,
- xlim=None, ylim=None, logx=False, logy=False, xticks=None,
- yticks=None, kind='line', sort_columns=False, fontsize=None,
- secondary_y=False, layout=None, **kwds):
+def _plot(data, x=None, y=None, subplots=False,
+ ax=None, kind='line', **kwds):
+ kind = _get_standard_kind(kind.lower().strip())
+ if kind in _all_kinds:
+ klass = _plot_klass[kind]
+ else:
+ raise ValueError('Invalid chart type given %s' % kind)
- """
- Make line, bar, or scatter plots of DataFrame series with the index on the x-axis
- using matplotlib / pylab.
+ from pandas import DataFrame
+ if kind in _dataframe_kinds:
+ if isinstance(data, DataFrame):
+ plot_obj = klass(data, x=x, y=y, subplots=subplots, ax=ax,
+ kind=kind, **kwds)
+ else:
+ raise ValueError('Invalid chart type given %s' % kind)
- Parameters
- ----------
- frame : DataFrame
- x : label or position, default None
+ elif kind in _series_kinds:
+ if isinstance(data, DataFrame):
+ if y is None and subplots is False:
+ msg = "{0} requires either y column or 'subplots=True'"
+ raise ValueError(msg.format(kind))
+ elif y is not None:
+ if com.is_integer(y) and not data.columns.holds_integer():
+ y = data.columns[y]
+ data = data[y] # converted to series actually
+ data.index.name = y
+ plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
+ else:
+ if isinstance(data, DataFrame):
+ if x is not None:
+ if com.is_integer(x) and not data.columns.holds_integer():
+ x = data.columns[x]
+ data = data.set_index(x)
+
+ if y is not None:
+ if com.is_integer(y) and not data.columns.holds_integer():
+ y = data.columns[y]
+ label = x if x is not None else data.index.name
+ label = kwds.pop('label', label)
+ series = data[y]
+ series.index.name = label
+
+ for kw in ['xerr', 'yerr']:
+ if (kw in kwds) and \
+ (isinstance(kwds[kw], string_types) or
+ com.is_integer(kwds[kw])):
+ try:
+ kwds[kw] = data[kwds[kw]]
+ except (IndexError, KeyError, TypeError):
+ pass
+ data = series
+ plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
+
+ plot_obj.generate()
+ plot_obj.draw()
+ return plot_obj.result
+
+
+df_kind = """- 'scatter' : scatter plot
+ - 'hexbin' : hexbin plot"""
+series_kind = ""
+
+df_coord = """x : label or position, default None
y : label or position, default None
- Allows plotting of one column versus another
- yerr : DataFrame (with matching labels), Series, list-type (tuple, list,
- ndarray), or str of column name containing y error values
- xerr : similar functionality as yerr, but for x error values
+ Allows plotting of one column versus another"""
+series_coord = ""
+
+df_unique = """stacked : boolean, default False in line and
+ bar plots, and True in area plot. If True, create stacked plot.
+ sort_columns : boolean, default False
+ Sort column names to determine plot ordering
+ secondary_y : boolean or sequence, default False
+ Whether to plot on the secondary y-axis
+ If a list/tuple, which columns to plot on secondary y-axis
+"""
+series_unique = """label : label argument to provide to plot
+ secondary_y : boolean or sequence of ints, default False
+ If True then y-axis will be on the right"""
+
+df_ax = """ax : matplotlib axes object, default None
subplots : boolean, default False
- Make separate subplots for each time series
+ Make separate subplots for each column
sharex : boolean, default True
In case subplots=True, share x axis
sharey : boolean, default False
In case subplots=True, share y axis
+ layout : tuple (optional)
+ (rows, columns) for the layout of subplots"""
+series_ax = """ax : matplotlib axes object
+ If not passed, uses gca()"""
+
+df_note = """- If `kind`='bar' or 'barh', you can specify relative alignments
+ for bar plot layout by `position` keyword.
+ From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)
+ - If `kind`='hexbin', you can control the size of the bins with the
+ `gridsize` argument. By default, a histogram of the counts around each
+ `(x, y)` point is computed. You can specify alternative aggregations
+ by passing values to the `C` and `reduce_C_function` arguments.
+ `C` specifies the value at each `(x, y)` point and `reduce_C_function`
+ is a function of one argument that reduces all the values in a bin to
+ a single number (e.g. `mean`, `max`, `sum`, `std`)."""
+series_note = ""
+
+_shared_doc_df_kwargs = dict(klass='DataFrame', klass_kind=df_kind,
+ klass_coord=df_coord, klass_ax=df_ax,
+ klass_unique=df_unique, klass_note=df_note)
+_shared_doc_series_kwargs = dict(klass='Series', klass_kind=series_kind,
+ klass_coord=series_coord, klass_ax=series_ax,
+ klass_unique=series_unique,
+ klass_note=series_note)
+
+_shared_docs['plot'] = """
+ Make plots of %(klass)s using matplotlib / pylab.
+
+ Parameters
+ ----------
+ data : %(klass)s
+ %(klass_coord)s
+ kind : str
+ - 'line' : line plot (default)
+ - 'bar' : vertical bar plot
+ - 'barh' : horizontal bar plot
+ - 'hist' : histogram
+ - 'box' : boxplot
+ - 'kde' : Kernel Density Estimation plot
+ - 'density' : same as 'kde'
+ - 'area' : area plot
+ - 'pie' : pie plot
+ %(klass_kind)s
+ %(klass_ax)s
+ figsize : a tuple (width, height) in inches
use_index : boolean, default True
Use index as ticks for x axis
- stacked : boolean, default False
- If True, create stacked bar plot. Only valid for DataFrame input
- sort_columns: boolean, default False
- Sort column names to determine plot ordering
title : string
Title to use for the plot
grid : boolean, default None (matlab style default)
Axis grid lines
legend : False/True/'reverse'
Place legend on axis subplots
-
- ax : matplotlib axis object, default None
style : list or dict
matplotlib line style per column
- kind : {'line', 'bar', 'barh', 'hist', 'kde', 'density', 'area', 'box', 'scatter', 'hexbin'}
- line : line plot
- bar : vertical bar plot
- barh : horizontal bar plot
- hist : histogram
- kde/density : Kernel Density Estimation plot
- area : area plot
- box : box plot
- scatter : scatter plot
- hexbin : hexbin plot
logx : boolean, default False
Use log scaling on x axis
logy : boolean, default False
@@ -2309,12 +2392,8 @@ def plot_frame(frame=None, x=None, y=None, subplots=False, sharex=True,
ylim : 2-tuple/list
rot : int, default None
Rotation for ticks
- secondary_y : boolean or sequence, default False
- Whether to plot on the secondary y-axis
- If a list/tuple, which columns to plot on secondary y-axis
- mark_right: boolean, default True
- When using a secondary_y axis, should the legend label the axis of
- the various columns automatically
+ fontsize : int, default None
+ Font size for ticks
colormap : str or matplotlib colormap object, default None
Colormap to select colors from. If string, load colormap with that name
from matplotlib.
@@ -2329,12 +2408,19 @@ def plot_frame(frame=None, x=None, y=None, subplots=False, sharex=True,
If True, draw a table using the data in the DataFrame and the data will
be transposed to meet matplotlib's default layout.
If a Series or DataFrame is passed, use passed data to draw a table.
+ yerr : DataFrame, Series, array-like, dict and str
+ See :ref:`Plotting with Error Bars <visualization.errorbars>` for detail.
+ xerr : same types as yerr.
+ %(klass_unique)s
+ mark_right : boolean, default True
+ When using a secondary_y axis, automatically mark the column
+ labels with "(right)" in the legend
kwds : keywords
Options to pass to matplotlib plotting method
Returns
-------
- ax_or_axes : matplotlib.AxesSubplot or list of them
+ axes : matplotlib.AxesSubplot or np.array of them
Notes
-----
@@ -2349,178 +2435,64 @@ def plot_frame(frame=None, x=None, y=None, subplots=False, sharex=True,
If `kind`='scatter' and the argument `c` is the name of a dataframe column,
the values of that column are used to color each point.
+ - See matplotlib documentation online for more on this subject
+ %(klass_note)s
"""
- kind = _get_standard_kind(kind.lower().strip())
- if kind in _all_kinds:
- klass = _plot_klass[kind]
- else:
- raise ValueError('Invalid chart type given %s' % kind)
-
- if kind in _dataframe_kinds:
- plot_obj = klass(frame, x=x, y=y, kind=kind, subplots=subplots,
- rot=rot,legend=legend, ax=ax, style=style,
- fontsize=fontsize, use_index=use_index, sharex=sharex,
- sharey=sharey, xticks=xticks, yticks=yticks,
- xlim=xlim, ylim=ylim, title=title, grid=grid,
- figsize=figsize, logx=logx, logy=logy,
- sort_columns=sort_columns, secondary_y=secondary_y,
- layout=layout, **kwds)
- elif kind in _series_kinds:
- if y is None and subplots is False:
- msg = "{0} requires either y column or 'subplots=True'"
- raise ValueError(msg.format(kind))
- elif y is not None:
- if com.is_integer(y) and not frame.columns.holds_integer():
- y = frame.columns[y]
- frame = frame[y] # converted to series actually
- frame.index.name = y
-
- plot_obj = klass(frame, kind=kind, subplots=subplots,
- rot=rot,legend=legend, ax=ax, style=style,
- fontsize=fontsize, use_index=use_index, sharex=sharex,
- sharey=sharey, xticks=xticks, yticks=yticks,
- xlim=xlim, ylim=ylim, title=title, grid=grid,
- figsize=figsize, layout=layout,
- sort_columns=sort_columns, **kwds)
- else:
- if x is not None:
- if com.is_integer(x) and not frame.columns.holds_integer():
- x = frame.columns[x]
- frame = frame.set_index(x)
-
- if y is not None:
- if com.is_integer(y) and not frame.columns.holds_integer():
- y = frame.columns[y]
- label = x if x is not None else frame.index.name
- label = kwds.pop('label', label)
- ser = frame[y]
- ser.index.name = label
-
- for kw in ['xerr', 'yerr']:
- if (kw in kwds) and \
- (isinstance(kwds[kw], string_types) or com.is_integer(kwds[kw])):
- try:
- kwds[kw] = frame[kwds[kw]]
- except (IndexError, KeyError, TypeError):
- pass
-
- return plot_series(ser, label=label, kind=kind,
- use_index=use_index,
- rot=rot, xticks=xticks, yticks=yticks,
- xlim=xlim, ylim=ylim, ax=ax, style=style,
- grid=grid, logx=logx, logy=logy,
- secondary_y=secondary_y, title=title,
- figsize=figsize, fontsize=fontsize, **kwds)
-
- else:
- plot_obj = klass(frame, kind=kind, subplots=subplots, rot=rot,
- legend=legend, ax=ax, style=style, fontsize=fontsize,
- use_index=use_index, sharex=sharex, sharey=sharey,
- xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim,
- title=title, grid=grid, figsize=figsize, logx=logx,
- logy=logy, sort_columns=sort_columns,
- secondary_y=secondary_y, layout=layout, **kwds)
-
- plot_obj.generate()
- plot_obj.draw()
- return plot_obj.result
-
-
-def plot_series(series, label=None, kind='line', use_index=True, rot=None,
+@Appender(_shared_docs['plot'] % _shared_doc_df_kwargs)
+def plot_frame(data, x=None, y=None, kind='line', ax=None, # Dataframe unique
+ subplots=False, sharex=True, sharey=False, layout=None, # Dataframe unique
+ figsize=None, use_index=True, title=None, grid=None,
+ legend=True, style=None, logx=False, logy=False, loglog=False,
+ xticks=None, yticks=None, xlim=None, ylim=None,
+ rot=None, fontsize=None, colormap=None, table=False,
+ yerr=None, xerr=None,
+ secondary_y=False, sort_columns=False, # Dataframe unique
+ **kwds):
+ return _plot(data, kind=kind, x=x, y=y, ax=ax,
+ subplots=subplots, sharex=sharex, sharey=sharey,
+ layout=layout, figsize=figsize, use_index=use_index,
+ title=title, grid=grid, legend=legend,
+ style=style, logx=logx, logy=logy, loglog=loglog,
+ xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim,
+ rot=rot, fontsize=fontsize, colormap=colormap, table=table,
+ yerr=yerr, xerr=xerr,
+ secondary_y=secondary_y, sort_columns=sort_columns,
+ **kwds)
+
+
+@Appender(_shared_docs['plot'] % _shared_doc_series_kwargs)
+def plot_series(data, kind='line', ax=None, # Series unique
+ figsize=None, use_index=True, title=None, grid=None,
+ legend=True, style=None, logx=False, logy=False, loglog=False,
xticks=None, yticks=None, xlim=None, ylim=None,
- ax=None, style=None, grid=None, legend=False, logx=False,
- logy=False, secondary_y=False, **kwds):
- """
- Plot the input series with the index on the x-axis using matplotlib
-
- Parameters
- ----------
- label : label argument to provide to plot
- kind : {'line', 'bar', 'barh', 'hist', 'kde', 'density', 'area', 'box'}
- line : line plot
- bar : vertical bar plot
- barh : horizontal bar plot
- hist : histogram
- kde/density : Kernel Density Estimation plot
- area : area plot
- box : box plot
- use_index : boolean, default True
- Plot index as axis tick labels
- rot : int, default None
- Rotation for tick labels
- xticks : sequence
- Values to use for the xticks
- yticks : sequence
- Values to use for the yticks
- xlim : 2-tuple/list
- ylim : 2-tuple/list
- ax : matplotlib axis object
- If not passed, uses gca()
- style : string, default matplotlib default
- matplotlib line style to use
- grid : matplotlib grid
- legend: matplotlib legend
- logx : boolean, default False
- Use log scaling on x axis
- logy : boolean, default False
- Use log scaling on y axis
- loglog : boolean, default False
- Use log scaling on both x and y axes
- secondary_y : boolean or sequence of ints, default False
- If True then y-axis will be on the right
- figsize : a tuple (width, height) in inches
- position : float
- Specify relative alignments for bar plot layout.
- From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)
- table : boolean, Series or DataFrame, default False
- If True, draw a table using the data in the Series and the data will
- be transposed to meet matplotlib's default layout.
- If a Series or DataFrame is passed, use passed data to draw a table.
- kwds : keywords
- Options to pass to matplotlib plotting method
-
- Notes
- -----
- See matplotlib documentation online for more on this subject
- """
-
- kind = _get_standard_kind(kind.lower().strip())
- if kind in _common_kinds or kind in _series_kinds:
- klass = _plot_klass[kind]
- else:
- raise ValueError('Invalid chart type given %s' % kind)
+ rot=None, fontsize=None, colormap=None, table=False,
+ yerr=None, xerr=None,
+ label=None, secondary_y=False, # Series unique
+ **kwds):
+ import matplotlib.pyplot as plt
"""
- If no axis is specified, we check whether there are existing figures.
- If so, we get the current axis and check whether yaxis ticks are on the
- right. Ticks for the plot of the series will be on the right unless
- there is at least one axis with ticks on the left.
-
- If we do not check for whether there are existing figures, _gca() will
- create a figure with the default figsize, causing the figsize= parameter to
+ If no axes is specified, check whether there are existing figures
+ If there is no existing figures, _gca() will
+ create a figure with the default figsize, causing the figsize=parameter to
be ignored.
"""
- import matplotlib.pyplot as plt
if ax is None and len(plt.get_fignums()) > 0:
ax = _gca()
ax = getattr(ax, 'left_ax', ax)
-
# is there harm in this?
if label is None:
- label = series.name
-
- plot_obj = klass(series, kind=kind, rot=rot, logx=logx, logy=logy,
- ax=ax, use_index=use_index, style=style,
- xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim,
- legend=legend, grid=grid, label=label,
- secondary_y=secondary_y, **kwds)
-
- plot_obj.generate()
- plot_obj.draw()
-
- # plot_obj.ax is None if we created the first figure
- return plot_obj.result
+ label = data.name
+ return _plot(data, kind=kind, ax=ax,
+ figsize=figsize, use_index=use_index, title=title,
+ grid=grid, legend=legend,
+ style=style, logx=logx, logy=logy, loglog=loglog,
+ xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim,
+ rot=rot, fontsize=fontsize, colormap=colormap, table=table,
+ yerr=yerr, xerr=xerr,
+ label=label, secondary_y=secondary_y,
+ **kwds)
_shared_docs['boxplot'] = """
@@ -2573,7 +2545,6 @@ def boxplot(data, column=None, by=None, ax=None, fontsize=None,
**kwds):
# validate return_type:
- valid_types = (None, 'axes', 'dict', 'both')
if return_type not in BoxPlot._valid_return_types:
raise ValueError("return_type must be {None, 'axes', 'dict', 'both'}")
@@ -2586,11 +2557,11 @@ def _get_colors():
return _get_standard_colors(color=kwds.get('color'), num_colors=1)
def maybe_color_bp(bp):
- if 'color' not in kwds :
+ if 'color' not in kwds:
from matplotlib.artist import setp
- setp(bp['boxes'],color=colors[0],alpha=1)
- setp(bp['whiskers'],color=colors[0],alpha=1)
- setp(bp['medians'],color=colors[2],alpha=1)
+ setp(bp['boxes'], color=colors[0], alpha=1)
+ setp(bp['whiskers'], color=colors[0], alpha=1)
+ setp(bp['medians'], color=colors[2], alpha=1)
def plot_group(keys, values, ax):
keys = [com.pprint_thing(x) for x in keys]
@@ -2622,7 +2593,8 @@ def plot_group(keys, values, ax):
if by is not None:
result = _grouped_plot_by_column(plot_group, data, columns=columns,
by=by, grid=grid, figsize=figsize,
- ax=ax, layout=layout, return_type=return_type)
+ ax=ax, layout=layout,
+ return_type=return_type)
else:
if layout is not None:
raise ValueError("The 'layout' keyword is not supported when "
@@ -2662,7 +2634,8 @@ def format_date_labels(ax, rot):
pass
-def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False, **kwargs):
+def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False,
+ **kwargs):
"""
Make a scatter plot from two DataFrame columns
| Branched off of https://github.com/pydata/pandas/pull/8037/files
just a couple of minor tweaks to that and some PEP8 stuff.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8459 | 2014-10-04T13:34:22Z | 2014-10-04T15:09:16Z | 2014-10-04T15:09:16Z | 2015-08-18T12:45:00Z |
BUG: type diversity breaks alignment | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 2776f6f9fcb35..cfd66a3a3829e 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -1007,3 +1007,4 @@ Bug Fixes
- Bug in Index.intersection on non-monotonic non-unique indexes (:issue:`8362`).
- Bug in masked series assignment where mismatching types would break alignment (:issue:`8387`)
- Bug in NDFrame.equals gives false negatives with dtype=object (:issue:`8437`)
+- Bug in assignment with indexer where type diversity would break alignment (:issue:`8258`)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 27a31a13a0259..8a77cc85efced 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -439,16 +439,10 @@ def can_do_equal_len():
if isinstance(value, ABCDataFrame) and value.ndim > 1:
for item in labels:
-
# align to
- if item in value:
- v = value[item]
- i = self.obj[item].index
- v = v.reindex(i & v.index)
-
- setter(item, v.values)
- else:
- setter(item, np.nan)
+ v = np.nan if item not in value else \
+ self._align_series(indexer[0], value[item])
+ setter(item, v)
# we have an equal len ndarray/convertible to our labels
elif np.array(value).ndim == 2:
@@ -511,6 +505,10 @@ def _align_series(self, indexer, ser):
if isinstance(indexer, tuple):
+ # flatten np.ndarray indexers
+ ravel = lambda i: i.ravel() if isinstance(i, np.ndarray) else i
+ indexer = tuple(map(ravel, indexer))
+
aligners = [not _is_null_slice(idx) for idx in indexer]
sum_aligners = sum(aligners)
single_aligner = sum_aligners == 1
@@ -536,12 +534,11 @@ def _align_series(self, indexer, ser):
# series, so need to broadcast (see GH5206)
if (sum_aligners == self.ndim and
all([com._is_sequence(_) for _ in indexer])):
- ser = ser.reindex(obj.axes[0][indexer[0].ravel()],
- copy=True).values
+ ser = ser.reindex(obj.axes[0][indexer[0]], copy=True).values
# single indexer
if len(indexer) > 1:
- l = len(indexer[1].ravel())
+ l = len(indexer[1])
ser = np.tile(ser, l).reshape(l, -1).T
return ser
@@ -557,7 +554,7 @@ def _align_series(self, indexer, ser):
if not is_list_like(new_ix):
new_ix = Index([new_ix])
else:
- new_ix = Index(new_ix.ravel())
+ new_ix = Index(new_ix)
if ser.index.equals(new_ix) or not len(new_ix):
return ser.values.copy()
@@ -1765,4 +1762,3 @@ def _maybe_droplevels(index, key):
pass
return index
-
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 700eb8591fdf9..79c8647948cd1 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -1405,6 +1405,7 @@ def test_setitem_frame(self):
# key is unaligned with values
f = self.mixed_frame.copy()
piece = f.ix[:2, ['A']]
+ piece.index = f.index[-2:]
key = (slice(-2, None), ['A', 'B'])
f.ix[key] = piece
piece['B'] = np.nan
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 7831fe811c2ff..7213aaafd1376 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1031,11 +1031,12 @@ def test_loc_setitem_frame(self):
def test_loc_setitem_frame_multiples(self):
-
# multiple setting
df = DataFrame({ 'A' : ['foo','bar','baz'],
'B' : Series(range(3),dtype=np.int64) })
- df.loc[0:1] = df.loc[1:2]
+ rhs = df.loc[1:2]
+ rhs.index = df.index[0:2]
+ df.loc[0:1] = rhs
expected = DataFrame({ 'A' : ['bar','baz','baz'],
'B' : Series([1,2,2],dtype=np.int64) })
assert_frame_equal(df, expected)
@@ -1047,8 +1048,9 @@ def test_loc_setitem_frame_multiples(self):
expected = DataFrame({ 'date' : [Timestamp('20000101'),Timestamp('20000102'),Timestamp('20000101'),
Timestamp('20000102'),Timestamp('20000103')],
'val' : Series([0,1,0,1,2],dtype=np.int64) })
-
- df.loc[2:4] = df.loc[0:2]
+ rhs = df.loc[0:2]
+ rhs.index = df.index[2:5]
+ df.loc[2:4] = rhs
assert_frame_equal(df, expected)
def test_iloc_getitem_frame(self):
@@ -3987,6 +3989,54 @@ def test_float_index_at_iat(self):
for i in range(len(s)):
self.assertEqual(s.iat[i], i + 1)
+ def test_rhs_alignment(self):
+ # GH8258, tests that both rows & columns are aligned to what is
+ # assigned to. covers both uniform data-type & multi-type cases
+ def run_tests(df, rhs, right):
+ # label, index, slice
+ r, i, s = list('bcd'), [1, 2, 3], slice(1, 4)
+ c, j, l = ['joe', 'jolie'], [1, 2], slice(1, 3)
+
+ left = df.copy()
+ left.loc[r, c] = rhs
+ assert_frame_equal(left, right)
+
+ left = df.copy()
+ left.iloc[i, j] = rhs
+ assert_frame_equal(left, right)
+
+ left = df.copy()
+ left.ix[s, l] = rhs
+ assert_frame_equal(left, right)
+
+ left = df.copy()
+ left.ix[i, j] = rhs
+ assert_frame_equal(left, right)
+
+ left = df.copy()
+ left.ix[r, c] = rhs
+ assert_frame_equal(left, right)
+
+ xs = np.arange(20).reshape(5, 4)
+ cols = ['jim', 'joe', 'jolie', 'joline']
+ df = pd.DataFrame(xs, columns=cols, index=list('abcde'))
+
+ # right hand side; permute the indices and multiplpy by -2
+ rhs = - 2 * df.iloc[3:0:-1, 2:0:-1]
+
+ # expected `right` result; just multiply by -2
+ right = df.copy()
+ right.iloc[1:4, 1:3] *= -2
+
+ # run tests with uniform dtypes
+ run_tests(df, rhs, right)
+
+ # make frames multi-type & re-run tests
+ for frame in [df, rhs, right]:
+ frame['joe'] = frame['joe'].astype('float64')
+ frame['jolie'] = frame['jolie'].map('@{0}'.format)
+
+ run_tests(df, rhs, right)
class TestSeriesNoneCoercion(tm.TestCase):
EXPECTED_RESULTS = [
| closes https://github.com/pydata/pandas/issues/8258, but more generally, on pandas master, assignment with indexer will align _both rows and columns_ if all columns have the same type:
```
>>> cols, idx = ['jim', 'joe', 'jolie'], ['first', 'last']
>>> vals = np.arange(1, 7).reshape(2, 3, order='F')
>>> df = DataFrame(vals, columns=cols, index=idx)
>>> left, rhs = df.copy(), - df.iloc[::-1, -2::-1]
>>> print(left, rhs, sep='\n')
jim joe jolie
first 1 3 5
last 2 4 6
joe jim
last -4 -2
first -3 -1
>>>
>>> left.loc[:, ['jim', 'joe']] = rhs
>>> left
jim joe jolie
first -1 -3 5
last -2 -4 6
```
However, if I change the type of a column even _outside_ the section which gets assigned to, _only columns_ are aligned:
```
>>> df = DataFrame(vals, columns=cols, index=idx)
>>> df['jolie'] = df['jolie'].astype('float64')
>>> left, rhs = df.copy(), - df.iloc[::-1, -2::-1]
>>> print(left, rhs, sep='\n')
jim joe jolie
first 1 3 5
last 2 4 6
joe jim
last -4 -2
first -3 -1
>>>
>>> left.loc[:, ['jim', 'joe']] = rhs
>>> left
jim joe jolie
first -2 -4 5
last -1 -3 6
```
Code-wise this is a bug, because [this line](https://github.com/pydata/pandas/blob/fccd7feabfe0bf15c30d712f3a4a4ff71e76ad4a/pandas/core/indexing.py#L446) is taking the _entire frame_'s index and re-indexes to that, regardless of the actual indexer which selects a section of the frame to assign to. That said, there are two places in tests where they rely on this behaviour, [here](https://github.com/pydata/pandas/blob/fccd7feabfe0bf15c30d712f3a4a4ff71e76ad4a/pandas/tests/test_frame.py#L1405) and [here](https://github.com/pydata/pandas/blob/fccd7feabfe0bf15c30d712f3a4a4ff71e76ad4a/pandas/tests/test_indexing.py#L1033).
| https://api.github.com/repos/pandas-dev/pandas/pulls/8457 | 2014-10-03T22:15:31Z | 2014-10-04T17:19:50Z | 2014-10-04T17:19:50Z | 2014-10-04T17:41:00Z |
PERF: optimize storage type for codes in Categoricals (GH8453) | diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst
index 669a39d437a34..a5f76fb2b5941 100644
--- a/doc/source/categorical.rst
+++ b/doc/source/categorical.rst
@@ -47,7 +47,7 @@ the `categories` array.
The categorical data type is useful in the following cases:
* A string variable consisting of only a few different values. Converting such a string
- variable to a categorical variable will save some memory.
+ variable to a categorical variable will save some memory, see :ref:`here<categorical.memory>`.
* The lexical order of a variable is not the same as the logical order ("one", "two", "three").
By converting to a categorical and specifying an order on the categories, sorting and
min/max will use the logical order instead of the lexical order.
@@ -633,6 +633,27 @@ The following differences to R's factor functions can be observed:
Gotchas
-------
+.. _categorical.memory:
+
+Memory Usage
+~~~~~~~~~~~~
+
+The memory usage of a ``Categorical`` is proportional to the length of the categories times the length of the data. In contrast,
+the an ``object`` dtype is a fixed function of the length of the data.
+
+.. ipython:: python
+
+ s = Series(['foo','bar']*1000)
+
+ # object dtype
+ s.nbytes
+
+ # category dtype
+ s.astype('category').nbytes
+
+Note that if the number of categories approaches the length of the data, the ``Categorical`` will use nearly (or more) memory than an
+equivalent ``object`` dtype representation.
+
Old style constructor usage
~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 5f8c2e7dcd30f..4fc808fe0409f 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -563,7 +563,7 @@ Categoricals in Series/DataFrame
:class:`~pandas.Categorical` can now be included in `Series` and `DataFrames` and gained new
methods to manipulate. Thanks to Jan Schulz for much of this API/implementation. (:issue:`3943`, :issue:`5313`, :issue:`5314`,
:issue:`7444`, :issue:`7839`, :issue:`7848`, :issue:`7864`, :issue:`7914`, :issue:`7768`, :issue:`8006`, :issue:`3678`,
-:issue:`8075`, :issue:`8076`, :issue:`8143`).
+:issue:`8075`, :issue:`8076`, :issue:`8143`, :issue:`8453`).
For full docs, see the :ref:`categorical introduction <categorical>` and the
:ref:`API documentation <api.categorical>`.
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index d2708890c5ec2..aa5fa29784912 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -67,7 +67,6 @@ def _maybe_to_categorical(array):
return array.values
return array
-
_codes_doc = """The category codes of this categorical.
Level codes are an array if integer which are the positions of the real
@@ -194,7 +193,7 @@ def __init__(self, values, categories=None, ordered=None, name=None, fastpath=Fa
if fastpath:
# fast path
- self._codes = values
+ self._codes = _coerce_codes_dtype(values, categories)
self.name = name
self.categories = categories
self.ordered = ordered
@@ -285,9 +284,9 @@ def __init__(self, values, categories=None, ordered=None, name=None, fastpath=Fa
ordered = True
self.ordered = False if ordered is None else ordered
- self._codes = codes
self.categories = categories
self.name = name
+ self._codes = _coerce_codes_dtype(codes, categories)
def copy(self):
""" Copy constructor. """
@@ -607,6 +606,7 @@ def add_categories(self, new_categories, inplace=False):
new_categories = self._validate_categories(new_categories)
cat = self if inplace else self.copy()
cat._categories = new_categories
+ cat._codes = _coerce_codes_dtype(cat._codes, new_categories)
if not inplace:
return cat
@@ -1105,6 +1105,12 @@ def __unicode__(self):
return result
+ def _maybe_coerce_indexer(self, indexer):
+ """ return an indexer coerced to the codes dtype """
+ if isinstance(indexer, np.ndarray) and indexer.dtype.kind == 'i':
+ indexer = indexer.astype(self._codes.dtype)
+ return indexer
+
def __getitem__(self, key):
""" Return an item. """
if isinstance(key, (int, np.integer)):
@@ -1114,6 +1120,7 @@ def __getitem__(self, key):
else:
return self.categories[i]
else:
+ key = self._maybe_coerce_indexer(key)
return Categorical(values=self._codes[key], categories=self.categories,
ordered=self.ordered, fastpath=True)
@@ -1181,6 +1188,8 @@ def __setitem__(self, key, value):
nan_pos = np.where(com.isnull(self.categories))[0]
lindexer[lindexer == -1] = nan_pos
+ key = self._maybe_coerce_indexer(key)
+ lindexer = self._maybe_coerce_indexer(lindexer)
self._codes[key] = lindexer
#### reduction ops ####
@@ -1395,6 +1404,22 @@ def _delegate_method(self, name, *args, **kwargs):
##### utility routines #####
+_int8_max = np.iinfo(np.int8).max
+_int16_max = np.iinfo(np.int16).max
+_int32_max = np.iinfo(np.int32).max
+
+def _coerce_codes_dtype(codes, categories):
+ """ coerce the code input array to an appropriate dtype """
+ codes = np.array(codes,copy=False)
+ l = len(categories)
+ if l < _int8_max:
+ return codes.astype('int8')
+ elif l < _int16_max:
+ return codes.astype('int16')
+ elif l < _int32_max:
+ return codes.astype('int32')
+ return codes.astype('int64')
+
def _get_codes_for_values(values, categories):
""""
utility routine to turn values into codes given the specified categories
@@ -1407,7 +1432,7 @@ def _get_codes_for_values(values, categories):
(hash_klass, vec_klass), vals = _get_data_algo(values, _hashtables)
t = hash_klass(len(categories))
t.map_locations(com._values_from_object(categories))
- return com._ensure_platform_int(t.lookup(values))
+ return _coerce_codes_dtype(t.lookup(values), categories)
def _convert_to_list_like(list_like):
if hasattr(list_like, "dtype"):
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index 7681289cf41ac..a2643b38e4133 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -714,12 +714,12 @@ def test_codes_immutable(self):
# Codes should be read only
c = Categorical(["a","b","c","a", np.nan])
- exp = np.array([0,1,2,0, -1])
+ exp = np.array([0,1,2,0,-1],dtype='int8')
self.assert_numpy_array_equal(c.codes, exp)
# Assignments to codes should raise
def f():
- c.codes = np.array([0,1,2,0,1])
+ c.codes = np.array([0,1,2,0,1],dtype='int8')
self.assertRaises(ValueError, f)
# changes in the codes array should raise
@@ -731,10 +731,10 @@ def f():
# But even after getting the codes, the original array should still be writeable!
c[4] = "a"
- exp = np.array([0,1,2,0, 0])
+ exp = np.array([0,1,2,0,0],dtype='int8')
self.assert_numpy_array_equal(c.codes, exp)
c._codes[4] = 2
- exp = np.array([0,1,2,0, 2])
+ exp = np.array([0,1,2,0, 2],dtype='int8')
self.assert_numpy_array_equal(c.codes, exp)
@@ -975,6 +975,28 @@ def f():
expected = Series([True,False,False],index=index)
tm.assert_series_equal(result, expected)
+ def test_codes_dtypes(self):
+
+ # GH 8453
+ result = Categorical(['foo','bar','baz'])
+ self.assertTrue(result.codes.dtype == 'int8')
+
+ result = Categorical(['foo%05d' % i for i in range(400) ])
+ self.assertTrue(result.codes.dtype == 'int16')
+
+ result = Categorical(['foo%05d' % i for i in range(40000) ])
+ self.assertTrue(result.codes.dtype == 'int32')
+
+ # adding cats
+ result = Categorical(['foo','bar','baz'])
+ self.assertTrue(result.codes.dtype == 'int8')
+ result = result.add_categories(['foo%05d' % i for i in range(400) ])
+ self.assertTrue(result.codes.dtype == 'int16')
+
+ # removing cats
+ result = result.remove_categories(['foo%05d' % i for i in range(300) ])
+ self.assertTrue(result.codes.dtype == 'int8')
+
def test_basic(self):
# test basic creation / coercion of categoricals
@@ -1192,7 +1214,7 @@ def test_series_delegations(self):
exp_categories = np.array([1,2,3])
self.assert_numpy_array_equal(s.cat.categories, exp_categories)
- exp_codes = Series(com._ensure_platform_int([0,1,2,0]))
+ exp_codes = Series([0,1,2,0],dtype='int8')
tm.assert_series_equal(s.cat.codes, exp_codes)
self.assertEqual(s.cat.ordered, True)
| closes #8453
So easy enough to optimize the dtype of the codes array depending on the number of categories. Most
of the time will simply be `int8`. So pretty good savings.
This doesn't completely solve the storage issues as currently `factorize` returns a `int64`, but can deal with that later (as might also need some more cython definitions).
And of course in the extreme case (where len(categories) == len(codes) you are better off with an object dtype).
```
In [1]: s = Series(['foo','bar']*1000)
In [2]: s.nbytes
Out[2]: 16000
In [3]: s.astype('category').nbytes
Out[3]: 2016
In [5]: s.astype('category').values.codes
Out[5]: array([1, 0, 1, ..., 0, 1, 0], dtype=int8)
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/8455 | 2014-10-03T20:55:41Z | 2014-10-04T16:38:15Z | 2014-10-04T16:38:15Z | 2014-10-04T16:38:15Z |
BUG: reset identity on legacy index pickles (GH8431) | diff --git a/pandas/core/index.py b/pandas/core/index.py
index b528a628234cc..da8edf13ff18f 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -843,6 +843,7 @@ def __setstate__(self, state):
np.ndarray.__setstate__(data, state)
self._data = data
+ self._reset_identity()
else:
raise Exception("invalid pickle state")
_unpickle_compat = __setstate__
@@ -3349,6 +3350,7 @@ def __setstate__(self, state):
self._set_names(names)
self.sortorder = sortorder
self._verify_integrity()
+ self._reset_identity()
def __getitem__(self, key):
if np.isscalar(key):
diff --git a/pandas/tests/data/s1-0.12.0.pkl b/pandas/tests/data/s1-0.12.0.pkl
new file mode 100644
index 0000000000000..0ce9cfdf3aa94
Binary files /dev/null and b/pandas/tests/data/s1-0.12.0.pkl differ
diff --git a/pandas/tests/data/s2-0.12.0.pkl b/pandas/tests/data/s2-0.12.0.pkl
new file mode 100644
index 0000000000000..2318be2d9978b
Binary files /dev/null and b/pandas/tests/data/s2-0.12.0.pkl differ
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 3001c4f09d982..5f240e896f57c 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -270,6 +270,15 @@ def test_view(self):
i_view = i.view()
self.assertEqual(i_view.name, 'Foo')
+ def test_legacy_pickle_identity(self):
+
+ # GH 8431
+ pth = tm.get_data_path()
+ s1 = pd.read_pickle(os.path.join(pth,'s1-0.12.0.pkl'))
+ s2 = pd.read_pickle(os.path.join(pth,'s2-0.12.0.pkl'))
+ self.assertFalse(s1.index.identical(s2.index))
+ self.assertFalse(s1.index.equals(s2.index))
+
def test_astype(self):
casted = self.intIndex.astype('i8')
@@ -532,7 +541,7 @@ def test_intersection(self):
result3 = idx1.intersection(idx3)
self.assertTrue(tm.equalContents(result3, expected3))
self.assertEqual(result3.name, expected3.name)
-
+
# non-monotonic non-unique
idx1 = Index(['A','B','A','C'])
idx2 = Index(['B','D'])
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 2483e0ebb32a5..7aaec511b82bf 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -630,6 +630,7 @@ def __setstate__(self, state):
np.ndarray.__setstate__(data, state)
self._data = data
+ self._reset_identity()
else:
raise Exception("invalid pickle state")
| closes #8431
| https://api.github.com/repos/pandas-dev/pandas/pulls/8454 | 2014-10-03T18:42:22Z | 2014-10-03T19:12:07Z | 2014-10-03T19:12:07Z | 2014-10-03T19:12:08Z |
Remove DataFrame.delevel | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 2776f6f9fcb35..9d03b7b38bea7 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -720,7 +720,8 @@ Deprecations
``ambiguous`` to allow for more flexibility in dealing with DST transitions.
Replace ``infer_dst=True`` with ``ambiguous='infer'`` for the same behavior (:issue:`7943`).
See :ref:`the docs<timeseries.timezone_ambiguous>` for more details.
-
+- Remove ``DataFrame.delevel`` method in favor of ``DataFrame.reset_index``
+ (:issue:`420`)
.. _whatsnew_0150.index_set_ops:
- The ``Index`` set operations ``+`` and ``-`` were deprecated in order to provide these for numeric type operations on certain index types. ``+`` can be replace by ``.union()`` or ``|``, and ``-`` by ``.difference()``. Further the method name ``Index.diff()`` is deprecated and can be replaced by ``Index.difference()`` (:issue:`8226`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index bc81ca2a2d2ad..cba2d3c5aa0e9 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2511,7 +2511,6 @@ def _maybe_casted_values(index, labels=None):
if not inplace:
return new_obj
- delevel = deprecate('delevel', reset_index)
#----------------------------------------------------------------------
# Reindex-based selection methods
| Part of #6581. Remove DataFrame.delevel which was previously deprecated in version 0.7.
@jreback
| https://api.github.com/repos/pandas-dev/pandas/pulls/8451 | 2014-10-03T15:26:32Z | 2014-10-03T18:00:03Z | 2014-10-03T18:00:03Z | 2014-10-05T15:33:47Z |
BUG: bug in df.info() when embedded categorical (related GH7619) | diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 542dc69aa35f4..a94e627952b75 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -245,7 +245,7 @@ def apply(self, func, **kwargs):
""" apply the function to my values; return a block if we are not one """
result = func(self.values)
if not isinstance(result, Block):
- result = make_block(values=result, placement=self.mgr_locs,)
+ result = make_block(values=_block_shape(result), placement=self.mgr_locs,)
return result
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index e05d7285592aa..7681289cf41ac 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -1306,6 +1306,18 @@ def test_repr(self):
self.assertEqual(exp,a.__unicode__())
+ def test_info(self):
+
+ # make sure it works
+ n = 2500
+ df = DataFrame({ 'int64' : np.random.randint(100,size=n) })
+ df['category'] = Series(np.array(list('abcdefghij')).take(np.random.randint(0,10,size=n))).astype('category')
+ df.isnull()
+ df.info()
+
+ df2 = df[df['category']=='d']
+ df2.info()
+
def test_groupby_sort(self):
# http://stackoverflow.com/questions/23814368/sorting-pandas-categorical-labels-after-groupby
| xref #7619
| https://api.github.com/repos/pandas-dev/pandas/pulls/8449 | 2014-10-03T12:05:53Z | 2014-10-03T12:33:46Z | 2014-10-03T12:33:46Z | 2014-10-03T12:33:46Z |
Add support of 'decimal' option to Series.to_csv and Dataframe.to_csv | diff --git a/pandas/core/format.py b/pandas/core/format.py
index 2773cc0c135c1..f46621d4b86bd 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -1169,7 +1169,7 @@ def __init__(self, obj, path_or_buf=None, sep=",", na_rep='', float_format=None,
mode='w', nanRep=None, encoding=None, quoting=None,
line_terminator='\n', chunksize=None, engine=None,
tupleize_cols=False, quotechar='"', date_format=None,
- doublequote=True, escapechar=None):
+ doublequote=True, escapechar=None, decimal='.'):
self.engine = engine # remove for 0.13
self.obj = obj
@@ -1181,6 +1181,7 @@ def __init__(self, obj, path_or_buf=None, sep=",", na_rep='', float_format=None,
self.sep = sep
self.na_rep = na_rep
self.float_format = float_format
+ self.decimal = decimal
self.header = header
self.index = index
@@ -1509,6 +1510,7 @@ def _save_chunk(self, start_i, end_i):
b = self.blocks[i]
d = b.to_native_types(slicer=slicer, na_rep=self.na_rep,
float_format=self.float_format,
+ decimal=self.decimal,
date_format=self.date_format)
for col_loc, col in zip(b.mgr_locs, d):
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 223cb4fe78e94..b7350dfd5d77c 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1073,7 +1073,7 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
mode='w', encoding=None, quoting=None,
quotechar='"', line_terminator='\n', chunksize=None,
tupleize_cols=False, date_format=None, doublequote=True,
- escapechar=None, **kwds):
+ escapechar=None, decimal='.', **kwds):
r"""Write DataFrame to a comma-separated values (csv) file
Parameters
@@ -1126,6 +1126,8 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
date_format : string, default None
Format string for datetime objects
cols : kwarg only alias of columns [deprecated]
+ decimal: string, default '.'
+ Character recognized as decimal separator. E.g. use ',' for European data
"""
formatter = fmt.CSVFormatter(self, path_or_buf,
@@ -1140,7 +1142,8 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
tupleize_cols=tupleize_cols,
date_format=date_format,
doublequote=doublequote,
- escapechar=escapechar)
+ escapechar=escapechar,
+ decimal=decimal)
formatter.save()
if path_or_buf is None:
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 354ccd2c94583..65419e2c29d75 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1161,7 +1161,7 @@ def _try_cast(self, element):
except: # pragma: no cover
return element
- def to_native_types(self, slicer=None, na_rep='', float_format=None,
+ def to_native_types(self, slicer=None, na_rep='', float_format=None, decimal='.',
**kwargs):
""" convert to our native types format, slicing if desired """
@@ -1171,10 +1171,22 @@ def to_native_types(self, slicer=None, na_rep='', float_format=None,
values = np.array(values, dtype=object)
mask = isnull(values)
values[mask] = na_rep
- if float_format:
+
+
+ if float_format and decimal != '.':
+ formatter = lambda v : (float_format % v).replace('.',decimal,1)
+ elif decimal != '.':
+ formatter = lambda v : ('%g' % v).replace('.',decimal,1)
+ elif float_format:
+ formatter = lambda v : float_format % v
+ else:
+ formatter = None
+
+ if formatter:
imask = (~mask).ravel()
values.flat[imask] = np.array(
- [float_format % val for val in values.ravel()[imask]])
+ [formatter(val) for val in values.ravel()[imask]])
+
return values.tolist()
def should_store(self, value):
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 37f66fc56ea56..e19e51fb9c9e5 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2239,7 +2239,7 @@ def from_csv(cls, path, sep=',', parse_dates=True, header=None,
def to_csv(self, path, index=True, sep=",", na_rep='',
float_format=None, header=False,
index_label=None, mode='w', nanRep=None, encoding=None,
- date_format=None):
+ date_format=None, decimal='.'):
"""
Write Series to a comma-separated values (csv) file
@@ -2267,6 +2267,8 @@ def to_csv(self, path, index=True, sep=",", na_rep='',
non-ascii, for python versions prior to 3
date_format: string, default None
Format string for datetime objects.
+ decimal: string, default '.'
+ Character recognized as decimal separator. E.g. use ',' for European data
"""
from pandas.core.frame import DataFrame
df = DataFrame(self)
@@ -2274,7 +2276,7 @@ def to_csv(self, path, index=True, sep=",", na_rep='',
result = df.to_csv(path, index=index, sep=sep, na_rep=na_rep,
float_format=float_format, header=header,
index_label=index_label, mode=mode, nanRep=nanRep,
- encoding=encoding, date_format=date_format)
+ encoding=encoding, date_format=date_format, decimal=decimal)
if path is None:
return result
diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py
index 9216b7a286c54..e2823571fe258 100644
--- a/pandas/tests/test_format.py
+++ b/pandas/tests/test_format.py
@@ -2343,7 +2343,22 @@ def test_csv_to_string(self):
df = DataFrame({'col' : [1,2]})
expected = ',col\n0,1\n1,2\n'
self.assertEqual(df.to_csv(), expected)
-
+
+ def test_to_csv_decimal(self):
+ # GH 8448
+ df = DataFrame({'col1' : [1], 'col2' : ['a'], 'col3' : [10.1] })
+
+ expected_default = ',col1,col2,col3\n0,1,a,10.1\n'
+ self.assertEqual(df.to_csv(), expected_default)
+
+ expected_european_excel = ';col1;col2;col3\n0;1;a;10,1\n'
+ self.assertEqual(df.to_csv(decimal=',',sep=';'), expected_european_excel)
+
+ expected_float_format_default = ',col1,col2,col3\n0,1,a,10.10\n'
+ self.assertEqual(df.to_csv(float_format = '%.2f'), expected_float_format_default)
+
+ expected_float_format = ';col1;col2;col3\n0;1;a;10,10\n'
+ self.assertEqual(df.to_csv(decimal=',',sep=';', float_format = '%.2f'), expected_float_format)
class TestSeriesFormatting(tm.TestCase):
_multiprocess_can_split_ = True
| closes #781
The 'decimal' option exists for read_csv method but not yet in 'to_csv' methods.
The lack of this option is particulary painful when we _have to_ work with Excel with European regional settings.
This modification add this option to both Series.to_csv and Dataframe.to_csv.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8448 | 2014-10-03T08:08:26Z | 2015-03-07T00:02:58Z | null | 2015-03-07T00:02:58Z |
BUG: NDFrame.equals gives false negatives with dtype=object (GH8437) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 92fd228ccd10e..2776f6f9fcb35 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -1006,3 +1006,4 @@ Bug Fixes
- Bug in ``DataFrame.dropna`` that interpreted non-existent columns in the subset argument as the 'last column' (:issue:`8303`)
- Bug in Index.intersection on non-monotonic non-unique indexes (:issue:`8362`).
- Bug in masked series assignment where mismatching types would break alignment (:issue:`8387`)
+- Bug in NDFrame.equals gives false negatives with dtype=object (:issue:`8437`)
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 354ccd2c94583..542dc69aa35f4 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -13,7 +13,7 @@
ABCSparseSeries, _infer_dtype_from_scalar,
_is_null_datelike_scalar,
is_timedelta64_dtype, is_datetime64_dtype,
- _possibly_infer_to_datetimelike)
+ _possibly_infer_to_datetimelike, array_equivalent)
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas.core.indexing import (_maybe_convert_indices, _length_of_indexer)
from pandas.core.categorical import Categorical, _maybe_to_categorical, _is_categorical
@@ -1057,7 +1057,7 @@ def func(c, v, o):
def equals(self, other):
if self.dtype != other.dtype or self.shape != other.shape: return False
- return np.array_equal(self.values, other.values)
+ return array_equivalent(self.values, other.values)
class NonConsolidatableMixIn(object):
diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py
index 0734da1ab09aa..fd457c93f92fa 100644
--- a/pandas/tests/test_generic.py
+++ b/pandas/tests/test_generic.py
@@ -1304,6 +1304,21 @@ def test_equals(self):
df2 = df1.set_index(['floats'], append=True)
self.assertTrue(df3.equals(df2))
+ # GH 8437
+ a = pd.Series([False, np.nan])
+ b = pd.Series([False, np.nan])
+ c = pd.Series(index=range(2))
+ d = pd.Series(index=range(2))
+ e = pd.Series(index=range(2))
+ f = pd.Series(index=range(2))
+ c[:-1] = d[:-1] = e[0] = f[0] = False
+ self.assertTrue(a.equals(a))
+ self.assertTrue(a.equals(b))
+ self.assertTrue(a.equals(c))
+ self.assertTrue(a.equals(d))
+ self.assertFalse(a.equals(e))
+ self.assertTrue(e.equals(f))
+
def test_describe_raises(self):
with tm.assertRaises(NotImplementedError):
tm.makePanel().describe()
| https://api.github.com/repos/pandas-dev/pandas/pulls/8443 | 2014-10-02T14:00:59Z | 2014-10-02T15:15:11Z | 2014-10-02T15:15:11Z | 2014-10-02T16:18:39Z | |
API: SQL class definitions renaming | diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 29ff08391e0e4..903a19be80f45 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -315,7 +315,7 @@ def read_sql_table(table_name, con, schema=None, index_col=None,
except sqlalchemy.exc.InvalidRequestError:
raise ValueError("Table %s not found" % table_name)
- pandas_sql = PandasSQLAlchemy(con, meta=meta)
+ pandas_sql = SQLDatabase(con, meta=meta)
table = pandas_sql.read_table(
table_name, index_col=index_col, coerce_float=coerce_float,
parse_dates=parse_dates, columns=columns)
@@ -374,7 +374,7 @@ def read_sql_query(sql, con, index_col=None, coerce_float=True, params=None,
"""
pandas_sql = pandasSQL_builder(con)
- return pandas_sql.read_sql(
+ return pandas_sql.read_query(
sql, index_col=index_col, params=params, coerce_float=coerce_float,
parse_dates=parse_dates)
@@ -388,7 +388,7 @@ def read_sql(sql, con, index_col=None, coerce_float=True, params=None,
----------
sql : string
SQL query to be executed or database table name.
- con : SQLAlchemy engine or DBAPI2 connection (legacy mode)
+ con : SQLAlchemy engine or DBAPI2 connection (fallback mode)
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
@@ -435,8 +435,8 @@ def read_sql(sql, con, index_col=None, coerce_float=True, params=None,
"""
pandas_sql = pandasSQL_builder(con)
- if isinstance(pandas_sql, PandasSQLLegacy):
- return pandas_sql.read_sql(
+ if isinstance(pandas_sql, SQLiteDatabase):
+ return pandas_sql.read_query(
sql, index_col=index_col, params=params,
coerce_float=coerce_float, parse_dates=parse_dates)
@@ -451,7 +451,7 @@ def read_sql(sql, con, index_col=None, coerce_float=True, params=None,
sql, index_col=index_col, coerce_float=coerce_float,
parse_dates=parse_dates, columns=columns)
else:
- return pandas_sql.read_sql(
+ return pandas_sql.read_query(
sql, index_col=index_col, params=params,
coerce_float=coerce_float, parse_dates=parse_dates)
@@ -551,14 +551,14 @@ def pandasSQL_builder(con, flavor=None, schema=None, meta=None,
# When support for DBAPI connections is removed,
# is_cursor should not be necessary.
if _is_sqlalchemy_engine(con):
- return PandasSQLAlchemy(con, schema=schema, meta=meta)
+ return SQLDatabase(con, schema=schema, meta=meta)
else:
if flavor == 'mysql':
warnings.warn(_MYSQL_WARNING, FutureWarning)
- return PandasSQLLegacy(con, flavor, is_cursor=is_cursor)
+ return SQLiteDatabase(con, flavor, is_cursor=is_cursor)
-class PandasSQLTable(PandasObject):
+class SQLTable(PandasObject):
"""
For mapping Pandas tables to SQL tables.
Uses fact that table is reflected by SQLAlchemy to
@@ -890,10 +890,24 @@ def to_sql(self, *args, **kwargs):
" or connection+sql flavor")
-class PandasSQLAlchemy(PandasSQL):
+class SQLDatabase(PandasSQL):
"""
This class enables convertion between DataFrame and SQL databases
using SQLAlchemy to handle DataBase abstraction
+
+ Parameters
+ ----------
+ engine : SQLAlchemy engine
+ Engine to connect with the database. Using SQLAlchemy makes it possible to use any DB supported by that
+ library.
+ schema : string, default None
+ Name of SQL schema in database to write to (if database flavor
+ supports this). If None, use default schema (default).
+ meta : SQLAlchemy MetaData object, default None
+ If provided, this MetaData object is used instead of a newly
+ created. This allows to specify database flavor specific
+ arguments in the MetaData object.
+
"""
def __init__(self, engine, schema=None, meta=None):
@@ -913,13 +927,86 @@ def execute(self, *args, **kwargs):
def read_table(self, table_name, index_col=None, coerce_float=True,
parse_dates=None, columns=None, schema=None):
- table = PandasSQLTable(
- table_name, self, index=index_col, schema=schema)
+ """Read SQL database table into a DataFrame.
+
+ Parameters
+ ----------
+ table_name : string
+ Name of SQL table in database
+ index_col : string, optional
+ Column to set as index
+ coerce_float : boolean, default True
+ Attempt to convert values to non-string, non-numeric objects (like
+ decimal.Decimal) to floating point. Can result in loss of Precision.
+ parse_dates : list or dict
+ - List of column names to parse as dates
+ - Dict of ``{column_name: format string}`` where format string is
+ strftime compatible in case of parsing string times or is one of
+ (D, s, ns, ms, us) in case of parsing integer timestamps
+ - Dict of ``{column_name: arg dict}``, where the arg dict corresponds
+ to the keyword arguments of :func:`pandas.to_datetime`
+ Especially useful with databases without native Datetime support,
+ such as SQLite
+ columns : list
+ List of column names to select from sql table
+ schema : string, default None
+ Name of SQL schema in database to query (if database flavor
+ supports this). If specified, this overwrites the default
+ schema of the SQLDatabase object.
+
+ Returns
+ -------
+ DataFrame
+
+ See also
+ --------
+ pandas.read_sql_table
+ SQLDatabase.read_query
+
+ """
+ table = SQLTable(table_name, self, index=index_col, schema=schema)
return table.read(coerce_float=coerce_float,
parse_dates=parse_dates, columns=columns)
-
- def read_sql(self, sql, index_col=None, coerce_float=True,
+
+ def read_query(self, sql, index_col=None, coerce_float=True,
parse_dates=None, params=None):
+ """Read SQL query into a DataFrame.
+
+ Parameters
+ ----------
+ sql : string
+ SQL query to be executed
+ index_col : string, optional
+ Column name to use as index for the returned DataFrame object.
+ coerce_float : boolean, default True
+ Attempt to convert values to non-string, non-numeric objects (like
+ decimal.Decimal) to floating point, useful for SQL result sets
+ params : list, tuple or dict, optional
+ List of parameters to pass to execute method. The syntax used
+ to pass parameters is database driver dependent. Check your
+ database driver documentation for which of the five syntax styles,
+ described in PEP 249's paramstyle, is supported.
+ Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
+ parse_dates : list or dict
+ - List of column names to parse as dates
+ - Dict of ``{column_name: format string}`` where format string is
+ strftime compatible in case of parsing string times or is one of
+ (D, s, ns, ms, us) in case of parsing integer timestamps
+ - Dict of ``{column_name: arg dict}``, where the arg dict corresponds
+ to the keyword arguments of :func:`pandas.to_datetime`
+ Especially useful with databases without native Datetime support,
+ such as SQLite
+
+ Returns
+ -------
+ DataFrame
+
+ See also
+ --------
+ read_sql_table : Read SQL database table into a DataFrame
+ read_sql
+
+ """
args = _convert_params(sql, params)
result = self.execute(*args)
@@ -935,12 +1022,41 @@ def read_sql(self, sql, index_col=None, coerce_float=True,
data_frame.set_index(index_col, inplace=True)
return data_frame
+
+ read_sql = read_query
def to_sql(self, frame, name, if_exists='fail', index=True,
index_label=None, schema=None, chunksize=None):
- table = PandasSQLTable(
- name, self, frame=frame, index=index, if_exists=if_exists,
- index_label=index_label, schema=schema)
+ """
+ Write records stored in a DataFrame to a SQL database.
+
+ Parameters
+ ----------
+ frame : DataFrame
+ name : string
+ Name of SQL table
+ if_exists : {'fail', 'replace', 'append'}, default 'fail'
+ - fail: If table exists, do nothing.
+ - replace: If table exists, drop it, recreate it, and insert data.
+ - append: If table exists, insert data. Create if does not exist.
+ index : boolean, default True
+ Write DataFrame index as a column
+ index_label : string or sequence, default None
+ Column label for index column(s). If None is given (default) and
+ `index` is True, then the index names are used.
+ A sequence should be given if the DataFrame uses MultiIndex.
+ schema : string, default None
+ Name of SQL schema in database to write to (if database flavor
+ supports this). If specified, this overwrites the default
+ schema of the SQLDatabase object.
+ chunksize : int, default None
+ If not None, then rows will be written in batches of this size at a
+ time. If None, all rows will be written at once.
+
+ """
+ table = SQLTable(name, self, frame=frame, index=index,
+ if_exists=if_exists, index_label=index_label,
+ schema=schema)
table.create()
table.insert(chunksize)
# check for potentially case sensitivity issues (GH7815)
@@ -972,8 +1088,7 @@ def drop_table(self, table_name, schema=None):
self.meta.clear()
def _create_sql_schema(self, frame, table_name, keys=None):
- table = PandasSQLTable(table_name, self, frame=frame, index=False,
- keys=keys)
+ table = SQLTable(table_name, self, frame=frame, index=False, keys=keys)
return str(table.sql_schema())
@@ -1032,9 +1147,9 @@ def _create_sql_schema(self, frame, table_name, keys=None):
"underscores.")
-class PandasSQLTableLegacy(PandasSQLTable):
+class SQLiteTable(SQLTable):
"""
- Patch the PandasSQLTable for legacy support.
+ Patch the SQLTable for fallback support.
Instead of a table variable just use the Create Table statement.
"""
@@ -1135,7 +1250,19 @@ def _sql_type_name(self, col):
return _SQL_TYPES[pytype_name][self.pd_sql.flavor]
-class PandasSQLLegacy(PandasSQL):
+class SQLiteDatabase(PandasSQL):
+ """
+ Version of SQLDatabase to support sqlite connections (fallback without
+ sqlalchemy). This should only be used internally.
+
+ For now still supports `flavor` argument to deal with 'mysql' database
+ for backwards compatibility, but this will be removed in future versions.
+
+ Parameters
+ ----------
+ con : sqlite connection object
+
+ """
def __init__(self, con, flavor, is_cursor=False):
self.is_cursor = is_cursor
@@ -1180,7 +1307,7 @@ def execute(self, *args, **kwargs):
ex = DatabaseError("Execution failed on sql '%s': %s" % (args[0], exc))
raise_with_traceback(ex)
- def read_sql(self, sql, index_col=None, coerce_float=True, params=None,
+ def read_query(self, sql, index_col=None, coerce_float=True, params=None,
parse_dates=None):
args = _convert_params(sql, params)
cursor = self.execute(*args)
@@ -1196,7 +1323,7 @@ def read_sql(self, sql, index_col=None, coerce_float=True, params=None,
if index_col is not None:
data_frame.set_index(index_col, inplace=True)
return data_frame
-
+
def _fetchall_as_list(self, cur):
result = cur.fetchall()
if not isinstance(result, list):
@@ -1230,9 +1357,8 @@ def to_sql(self, frame, name, if_exists='fail', index=True,
size at a time. If None, all rows will be written at once.
"""
- table = PandasSQLTableLegacy(
- name, self, frame=frame, index=index, if_exists=if_exists,
- index_label=index_label)
+ table = SQLiteTable(name, self, frame=frame, index=index,
+ if_exists=if_exists, index_label=index_label)
table.create()
table.insert(chunksize)
@@ -1246,15 +1372,15 @@ def has_table(self, name, schema=None):
return len(self.execute(query).fetchall()) > 0
def get_table(self, table_name, schema=None):
- return None # not supported in Legacy mode
+ return None # not supported in fallback mode
def drop_table(self, name, schema=None):
drop_sql = "DROP TABLE %s" % name
self.execute(drop_sql)
def _create_sql_schema(self, frame, table_name, keys=None):
- table = PandasSQLTableLegacy(table_name, self, frame=frame,
- index=False, keys=keys)
+ table = SQLiteTable(table_name, self, frame=frame, index=False,
+ keys=keys)
return str(table.sql_schema())
diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py
index 217114a00e980..c2d75f3ff2611 100644
--- a/pandas/io/tests/test_sql.py
+++ b/pandas/io/tests/test_sql.py
@@ -6,12 +6,12 @@
- Tests for the public API (only tests with sqlite3)
- `_TestSQLApi` base class
- `TestSQLApi`: test the public API with sqlalchemy engine
- - `TesySQLLegacyApi`: test the public API with DBAPI connection
+ - `TesySQLiteFallbackApi`: test the public API with a sqlite DBAPI connection
- Tests for the different SQL flavors (flavor specific type conversions)
- Tests for the sqlalchemy mode: `_TestSQLAlchemy` is the base class with
common methods, the different tested flavors (sqlite3, MySQL, PostgreSQL)
derive from the base class
- - Tests for the legacy mode (`TestSQLiteLegacy` and `TestMySQLLegacy`)
+ - Tests for the fallback mode (`TestSQLiteFallback` and `TestMySQLLegacy`)
"""
@@ -228,19 +228,19 @@ def _count_rows(self, table_name):
return result[0]
def _read_sql_iris(self):
- iris_frame = self.pandasSQL.read_sql("SELECT * FROM iris")
+ iris_frame = self.pandasSQL.read_query("SELECT * FROM iris")
self._check_iris_loaded_frame(iris_frame)
def _read_sql_iris_parameter(self):
query = SQL_STRINGS['read_parameters'][self.flavor]
params = ['Iris-setosa', 5.1]
- iris_frame = self.pandasSQL.read_sql(query, params=params)
+ iris_frame = self.pandasSQL.read_query(query, params=params)
self._check_iris_loaded_frame(iris_frame)
def _read_sql_iris_named_parameter(self):
query = SQL_STRINGS['read_named_parameters'][self.flavor]
params = {'name': 'Iris-setosa', 'length': 5.1}
- iris_frame = self.pandasSQL.read_sql(query, params=params)
+ iris_frame = self.pandasSQL.read_query(query, params=params)
self._check_iris_loaded_frame(iris_frame)
def _to_sql(self):
@@ -313,7 +313,7 @@ def _to_sql_append(self):
def _roundtrip(self):
self.drop_table('test_frame_roundtrip')
self.pandasSQL.to_sql(self.test_frame1, 'test_frame_roundtrip')
- result = self.pandasSQL.read_sql('SELECT * FROM test_frame_roundtrip')
+ result = self.pandasSQL.read_query('SELECT * FROM test_frame_roundtrip')
result.set_index('level_0', inplace=True)
# result.index.astype(int)
@@ -348,13 +348,13 @@ def _transaction_test(self):
except:
# ignore raised exception
pass
- res = self.pandasSQL.read_sql('SELECT * FROM test_trans')
+ res = self.pandasSQL.read_query('SELECT * FROM test_trans')
self.assertEqual(len(res), 0)
# Make sure when transaction is committed, rows do get inserted
with self.pandasSQL.run_transaction() as trans:
trans.execute(ins_sql)
- res2 = self.pandasSQL.read_sql('SELECT * FROM test_trans')
+ res2 = self.pandasSQL.read_query('SELECT * FROM test_trans')
self.assertEqual(len(res2), 1)
@@ -367,7 +367,7 @@ class _TestSQLApi(PandasSQLTest):
Base class to test the public API.
From this two classes are derived to run these tests for both the
- sqlalchemy mode (`TestSQLApi`) and the legacy mode (`TestSQLLegacyApi`).
+ sqlalchemy mode (`TestSQLApi`) and the fallback mode (`TestSQLiteFallbackApi`).
These tests are run with sqlite3. Specific tests for the different
sql flavours are included in `_TestSQLAlchemy`.
@@ -736,9 +736,9 @@ def _get_index_columns(self, tbl_name):
return ixs
-class TestSQLLegacyApi(_TestSQLApi):
+class TestSQLiteFallbackApi(_TestSQLApi):
"""
- Test the public legacy API
+ Test the public sqlite connection fallback API
"""
flavor = 'sqlite'
@@ -833,7 +833,7 @@ def connect(self):
def setup_connect(self):
try:
self.conn = self.connect()
- self.pandasSQL = sql.PandasSQLAlchemy(self.conn)
+ self.pandasSQL = sql.SQLDatabase(self.conn)
# to test if connection can be made:
self.conn.connect()
except sqlalchemy.exc.OperationalError:
@@ -871,7 +871,7 @@ def test_create_table(self):
temp_frame = DataFrame(
{'one': [1., 2., 3., 4.], 'two': [4., 3., 2., 1.]})
- pandasSQL = sql.PandasSQLAlchemy(temp_conn)
+ pandasSQL = sql.SQLDatabase(temp_conn)
pandasSQL.to_sql(temp_frame, 'temp_frame')
self.assertTrue(
@@ -883,7 +883,7 @@ def test_drop_table(self):
temp_frame = DataFrame(
{'one': [1., 2., 3., 4.], 'two': [4., 3., 2., 1.]})
- pandasSQL = sql.PandasSQLAlchemy(temp_conn)
+ pandasSQL = sql.SQLDatabase(temp_conn)
pandasSQL.to_sql(temp_frame, 'temp_frame')
self.assertTrue(
@@ -1302,7 +1302,7 @@ def test_schema_support(self):
engine2 = self.connect()
meta = sqlalchemy.MetaData(engine2, schema='other')
- pdsql = sql.PandasSQLAlchemy(engine2, meta=meta)
+ pdsql = sql.SQLDatabase(engine2, meta=meta)
pdsql.to_sql(df, 'test_schema_other2', index=False)
pdsql.to_sql(df, 'test_schema_other2', index=False, if_exists='replace')
pdsql.to_sql(df, 'test_schema_other2', index=False, if_exists='append')
@@ -1314,9 +1314,9 @@ def test_schema_support(self):
#------------------------------------------------------------------------------
#--- Test Sqlite / MySQL fallback
-class TestSQLiteLegacy(PandasSQLTest):
+class TestSQLiteFallback(PandasSQLTest):
"""
- Test the legacy mode against an in-memory sqlite database.
+ Test the fallback mode against an in-memory sqlite database.
"""
flavor = 'sqlite'
@@ -1331,7 +1331,7 @@ def drop_table(self, table_name):
def setUp(self):
self.conn = self.connect()
- self.pandasSQL = sql.PandasSQLLegacy(self.conn, 'sqlite')
+ self.pandasSQL = sql.SQLiteDatabase(self.conn, 'sqlite')
self._load_iris_data()
@@ -1339,7 +1339,7 @@ def setUp(self):
def test_invalid_flavor(self):
self.assertRaises(
- NotImplementedError, sql.PandasSQLLegacy, self.conn, 'oracle')
+ NotImplementedError, sql.SQLiteDatabase, self.conn, 'oracle')
def test_read_sql(self):
self._read_sql_iris()
@@ -1417,7 +1417,7 @@ def test_to_sql_save_index(self):
def test_transactions(self):
self._transaction_test()
-class TestMySQLLegacy(TestSQLiteLegacy):
+class TestMySQLLegacy(TestSQLiteFallback):
"""
Test the legacy mode against a MySQL database.
@@ -1451,7 +1451,7 @@ def setUp(self):
except self.driver.err.OperationalError:
raise nose.SkipTest("Can't connect to MySQL server")
- self.pandasSQL = sql.PandasSQLLegacy(self.conn, 'mysql')
+ self.pandasSQL = sql.SQLiteDatabase(self.conn, 'mysql')
self._load_iris_data()
self._load_test1_data()
| WIP, related to #7960
- [x] renaming of
- PandasSQLAlchemy -> SQLDatabase
- PandasSQLTable -> SQLTable
- PandasSQLLegacy -> SQLiteDatabase
- PandasSQLLegacyTable -> SQLiteTable
- SQLDatabase.read_sql -> read_query
- [ ] adding docstrings to public functions of SQLDatabase
- [x] read_query, read_table, to_sql
- [ ] has_table, drop_table, ..
- [ ] add docs on use of SQLDatabase
- [ ] add api docs for SQLDatabase
- [x] rename some mentions of 'legacy' to 'fallback'
| https://api.github.com/repos/pandas-dev/pandas/pulls/8440 | 2014-10-02T08:35:02Z | 2014-10-05T19:29:00Z | 2014-10-05T19:29:00Z | 2014-10-05T19:29:01Z |
DOC: mention 'category' in select_dtypes docstring | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 223cb4fe78e94..bc81ca2a2d2ad 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1903,6 +1903,7 @@ def select_dtypes(self, include=None, exclude=None):
this will return *all* object dtype columns
* See the `numpy dtype hierarchy
<http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html>`__
+ * To select Pandas categorical dtypes, use 'category'
Examples
--------
| Trivial update to select_dtypes docstring to hint on how to include Categorical types, as it's not part of the numpy type-hierarchy mentioned here.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8439 | 2014-10-02T02:31:14Z | 2014-10-02T06:41:41Z | 2014-10-02T06:41:41Z | 2014-10-02T06:41:56Z |
BUG: Groupby.transform related to BinGrouper and GH8046 (GH8430) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 22860a143476e..92fd228ccd10e 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -880,7 +880,7 @@ Bug Fixes
when matching block and manager items, when there's only one block there's no ambiguity (:issue:`7794`)
- Bug in putting a ``PeriodIndex`` into a ``Series`` would convert to ``int64`` dtype, rather than ``object`` of ``Periods`` (:issue:`7932`)
- Bug in HDFStore iteration when passing a where (:issue:`8014`)
-- Bug in DataFrameGroupby.transform when transforming with a passed non-sorted key (:issue:`8046`)
+- Bug in DataFrameGroupby.transform when transforming with a passed non-sorted key (:issue:`8046`, :issue:`8430`)
- Bug in repeated timeseries line and area plot may result in ``ValueError`` or incorrect kind (:issue:`7733`)
- Bug in inference in a MultiIndex with ``datetime.date`` inputs (:issue:`7888`)
- Bug in ``get`` where an ``IndexError`` would not cause the default value to be returned (:issue:`7725`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 9698d91b3ed8a..2e107e0b0e935 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -484,8 +484,7 @@ def _set_result_index_ordered(self, result):
indices = self.indices
# shortcut of we have an already ordered grouper
-
- if not Index(self.grouper.group_info[0]).is_monotonic:
+ if not self.grouper.is_monotonic:
index = Index(np.concatenate([ indices[v] for v in self.grouper.result_index ]))
result.index = index
result = result.sort_index()
@@ -1348,6 +1347,11 @@ def groups(self):
to_groupby = Index(to_groupby)
return self.axis.groupby(to_groupby.values)
+ @cache_readonly
+ def is_monotonic(self):
+ # return if my group orderings are monotonic
+ return Index(self.group_info[0]).is_monotonic
+
@cache_readonly
def group_info(self):
comp_ids, obs_group_ids = self._get_compressed_labels()
@@ -1739,6 +1743,11 @@ def indices(self):
i = bin
return indices
+ @cache_readonly
+ def group_info(self):
+ # for compat
+ return self.bins, self.binlabels, self.ngroups
+
@cache_readonly
def ngroups(self):
return len(self.binlabels)
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 3fdd7c3459c74..09763d53c017d 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -897,6 +897,11 @@ def demean(arr):
expected = people.groupby(key).apply(demean).groupby(key).mean()
assert_frame_equal(result, expected)
+ # GH 8430
+ df = tm.makeTimeDataFrame()
+ g = df.groupby(pd.TimeGrouper('M'))
+ g.transform(lambda x: x-1)
+
def test_transform_fast(self):
df = DataFrame( { 'id' : np.arange( 100000 ) / 3,
| closes #8430
xref #8046
| https://api.github.com/repos/pandas-dev/pandas/pulls/8434 | 2014-10-01T12:34:42Z | 2014-10-01T13:03:57Z | 2014-10-01T13:03:57Z | 2014-10-01T13:03:57Z |
TST: Adjust boxplot tests following MPL API change | diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 1cc5e2a99148b..d1d06862d003f 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -33,7 +33,7 @@ def _skip_if_mpl_14_or_dev_boxplot():
# Boxplot failures on 1.4 and 1.4.1
# Don't need try / except since that's done at class level
import matplotlib
- if matplotlib.__version__ in ('1.4.0', '1.5.x'):
+ if matplotlib.__version__ >= LooseVersion('1.4'):
raise nose.SkipTest("Matplotlib Regression in 1.4 and current dev.")
@@ -72,6 +72,11 @@ def setUp(self):
'weight': random.normal(161, 32, size=n),
'category': random.randint(4, size=n)})
+ if mpl.__version__ >= LooseVersion('1.4'):
+ self.bp_n_objects = 7
+ else:
+ self.bp_n_objects = 8
+
def tearDown(self):
tm.close()
@@ -1799,7 +1804,6 @@ def test_bar_log_subplots(self):
@slow
def test_boxplot(self):
- _skip_if_mpl_14_or_dev_boxplot()
df = self.hist_df
series = df['height']
numeric_cols = df._get_numeric_data().columns
@@ -1807,15 +1811,19 @@ def test_boxplot(self):
ax = _check_plot_works(df.plot, kind='box')
self._check_text_labels(ax.get_xticklabels(), labels)
- assert_array_equal(ax.xaxis.get_ticklocs(), np.arange(1, len(numeric_cols) + 1))
- self.assertEqual(len(ax.lines), 8 * len(numeric_cols))
+ assert_array_equal(ax.xaxis.get_ticklocs(),
+ np.arange(1, len(numeric_cols) + 1))
+ self.assertEqual(len(ax.lines),
+ self.bp_n_objects * len(numeric_cols))
- axes = _check_plot_works(df.plot, kind='box', subplots=True, logy=True)
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.plot, kind='box',
+ subplots=True, logy=True)
self._check_axes_shape(axes, axes_num=3, layout=(1, 3))
self._check_ax_scales(axes, yaxis='log')
for ax, label in zip(axes, labels):
self._check_text_labels(ax.get_xticklabels(), [label])
- self.assertEqual(len(ax.lines), 8)
+ self.assertEqual(len(ax.lines), self.bp_n_objects)
axes = series.plot(kind='box', rot=40)
self._check_ticks_props(axes, xrot=40, yrot=0)
@@ -1829,13 +1837,11 @@ def test_boxplot(self):
labels = [com.pprint_thing(c) for c in numeric_cols]
self._check_text_labels(ax.get_xticklabels(), labels)
assert_array_equal(ax.xaxis.get_ticklocs(), positions)
- self.assertEqual(len(ax.lines), 8 * len(numeric_cols))
+ self.assertEqual(len(ax.lines), self.bp_n_objects * len(numeric_cols))
@slow
def test_boxplot_vertical(self):
- _skip_if_mpl_14_or_dev_boxplot()
df = self.hist_df
- series = df['height']
numeric_cols = df._get_numeric_data().columns
labels = [com.pprint_thing(c) for c in numeric_cols]
@@ -1843,7 +1849,7 @@ def test_boxplot_vertical(self):
ax = df.plot(kind='box', rot=50, fontsize=8, vert=False)
self._check_ticks_props(ax, xrot=0, yrot=50, ylabelsize=8)
self._check_text_labels(ax.get_yticklabels(), labels)
- self.assertEqual(len(ax.lines), 8 * len(numeric_cols))
+ self.assertEqual(len(ax.lines), self.bp_n_objects * len(numeric_cols))
axes = _check_plot_works(df.plot, kind='box', subplots=True,
vert=False, logx=True)
@@ -1851,13 +1857,13 @@ def test_boxplot_vertical(self):
self._check_ax_scales(axes, xaxis='log')
for ax, label in zip(axes, labels):
self._check_text_labels(ax.get_yticklabels(), [label])
- self.assertEqual(len(ax.lines), 8)
+ self.assertEqual(len(ax.lines), self.bp_n_objects)
positions = np.array([3, 2, 8])
ax = df.plot(kind='box', positions=positions, vert=False)
self._check_text_labels(ax.get_yticklabels(), labels)
assert_array_equal(ax.yaxis.get_ticklocs(), positions)
- self.assertEqual(len(ax.lines), 8 * len(numeric_cols))
+ self.assertEqual(len(ax.lines), self.bp_n_objects * len(numeric_cols))
@slow
def test_boxplot_return_type(self):
| fliers on a boxplot are now 1 object instead of 2. [See here](https://github.com/matplotlib/matplotlib/issues/3544#issuecomment-57360910).
Takes care of one part of https://github.com/pydata/pandas/issues/8402
| https://api.github.com/repos/pandas-dev/pandas/pulls/8429 | 2014-09-30T19:54:44Z | 2014-10-04T14:09:10Z | 2014-10-04T14:09:10Z | 2017-04-05T02:05:59Z |
ENH: numerically stable rolling_skew and rolling_kurt | diff --git a/pandas/algos.pyx b/pandas/algos.pyx
index 62ee6ced84882..e7451f7ecdb1d 100644
--- a/pandas/algos.pyx
+++ b/pandas/algos.pyx
@@ -1331,144 +1331,105 @@ def roll_var(ndarray[double_t] input, int win, int minp, int ddof=1):
return output
+#----------------------------------------------------------------------
+# Rolling skewness and kurtosis
-#-------------------------------------------------------------------------------
-# Rolling skewness
@cython.boundscheck(False)
@cython.wraparound(False)
-def roll_skew(ndarray[double_t] input, int win, int minp):
+def roll_higher_moment(ndarray[double_t] input, int win, int minp, bint kurt):
+ """
+ Numerically stable implementation of skewness and kurtosis using a
+ Welford-like method. If `kurt` is True, rolling kurtosis is computed,
+ if False, rolling skewness.
+ """
cdef double val, prev
- cdef double x = 0, xx = 0, xxx = 0
- cdef Py_ssize_t nobs = 0, i
- cdef Py_ssize_t N = len(input)
+ cdef double mean_x = 0, s2dm_x = 0, s3dm_x = 0, s4dm_x = 0, rep = NaN
+ cdef double delta, delta_n, tmp
+ cdef Py_ssize_t i, nobs = 0, nrep = 0, N = len(input)
cdef ndarray[double_t] output = np.empty(N, dtype=float)
- # 3 components of the skewness equation
- cdef double A, B, C, R
-
minp = _check_minp(win, minp, N)
- with nogil:
- for i from 0 <= i < minp - 1:
- val = input[i]
+ minobs = max(minp, 4 if kurt else 3)
- # Not NaN
- if val == val:
- nobs += 1
- x += val
- xx += val * val
- xxx += val * val * val
-
- output[i] = NaN
-
- for i from minp - 1 <= i < N:
- val = input[i]
-
- if val == val:
- nobs += 1
- x += val
- xx += val * val
- xxx += val * val * val
-
- if i > win - 1:
- prev = input[i - win]
- if prev == prev:
- x -= prev
- xx -= prev * prev
- xxx -= prev * prev * prev
-
- nobs -= 1
- if nobs >= minp:
- A = x / nobs
- B = xx / nobs - A * A
- C = xxx / nobs - A * A * A - 3 * A * B
- if B <= 0 or nobs < 3:
- output[i] = NaN
+ for i from 0 <= i < N:
+ val = input[i]
+ prev = NaN if i < win else input[i - win]
+
+ if prev == prev:
+ # prev is not NaN, remove an observation...
+ nobs -= 1
+ if nobs < nrep:
+ # ...all non-NaN values were identical, remove a repeat
+ nrep -= 1
+ if nobs == nrep:
+ # We can get here both if all non-NaN were already identical
+ # or if nobs == 1 after removing the observation
+ if nrep == 0:
+ rep = NaN
+ mean_x = 0
else:
- R = sqrt(B)
- output[i] = ((sqrt(nobs * (nobs - 1.)) * C) /
- ((nobs-2) * R * R * R))
+ mean_x = rep
+ # This is redundant most of the time
+ s2dm_x = s3dm_x = s4dm_x = 0
else:
- output[i] = NaN
-
- return output
-
-#-------------------------------------------------------------------------------
-# Rolling kurtosis
-@cython.boundscheck(False)
-@cython.wraparound(False)
-def roll_kurt(ndarray[double_t] input,
- int win, int minp):
- cdef double val, prev
- cdef double x = 0, xx = 0, xxx = 0, xxxx = 0
- cdef Py_ssize_t nobs = 0, i
- cdef Py_ssize_t N = len(input)
-
- cdef ndarray[double_t] output = np.empty(N, dtype=float)
-
- # 5 components of the kurtosis equation
- cdef double A, B, C, D, R, K
-
- minp = _check_minp(win, minp, N)
- with nogil:
- for i from 0 <= i < minp - 1:
- val = input[i]
-
- # Not NaN
- if val == val:
- nobs += 1
-
- # seriously don't ask me why this is faster
- x += val
- xx += val * val
- xxx += val * val * val
- xxxx += val * val * val * val
-
- output[i] = NaN
-
- for i from minp - 1 <= i < N:
- val = input[i]
-
- if val == val:
- nobs += 1
- x += val
- xx += val * val
- xxx += val * val * val
- xxxx += val * val * val * val
-
- if i > win - 1:
- prev = input[i - win]
- if prev == prev:
- x -= prev
- xx -= prev * prev
- xxx -= prev * prev * prev
- xxxx -= prev * prev * prev * prev
-
- nobs -= 1
-
- if nobs >= minp:
- A = x / nobs
- R = A * A
- B = xx / nobs - R
- R = R * A
- C = xxx / nobs - R - 3 * A * B
- R = R * A
- D = xxxx / nobs - R - 6*B*A*A - 4*C*A
-
- if B == 0 or nobs < 4:
- output[i] = NaN
-
- else:
- K = (nobs * nobs - 1.)*D/(B*B) - 3*((nobs-1.)**2)
- K = K / ((nobs - 2.)*(nobs-3.))
-
- output[i] = K
+ # ...update mean and sums of raised differences from mean
+ delta = prev - mean_x
+ delta_n = delta / nobs
+ tmp = delta * delta_n * (nobs + 1)
+ if kurt:
+ s4dm_x -= ((tmp * ((nobs + 3) * nobs + 3) -
+ 6 * s2dm_x) * delta_n - 4 * s3dm_x) * delta_n
+ s3dm_x -= (tmp * (nobs + 2) - 3 * s2dm_x) * delta_n
+ s2dm_x -= tmp
+ mean_x -= delta_n
+ if val == val:
+ # val is not NaN, adding an observation...
+ nobs += 1
+ if val == rep:
+ # ...and adding a repeat
+ nrep += 1
else:
- output[i] = NaN
+ # ...and resetting repeats
+ nrep = 1
+ rep = val
+ if nobs == nrep:
+ # ...all non-NaN values are identical
+ mean_x = rep
+ s2dm_x = s3dm_x = s4dm_x = 0
+ else:
+ # ...update mean and sums of raised differences from mean
+ delta = val - mean_x
+ delta_n = delta / nobs
+ tmp = delta * delta_n * (nobs - 1)
+ if kurt:
+ s4dm_x += ((tmp * ((nobs - 3) * nobs + 3) +
+ 6 * s2dm_x) * delta_n - 4 * s3dm_x) * delta_n
+ s3dm_x += (tmp * (nobs - 2) - 3 * s2dm_x) * delta_n
+ s2dm_x += tmp
+ mean_x += delta_n
+
+ # Sums of even powers must be positive
+ if s2dm_x < 0 or s4dm_x < 0:
+ s2dm_x = s3dm_x = s4_dm_x = 0
+
+ if nobs < minobs or s2dm_x == 0:
+ output[i] = NaN
+ elif kurt:
+ # multiplications are cheap, divisions are not
+ tmp = s2dm_x * s2dm_x
+ output[i] = (nobs - 1) * (nobs * (nobs + 1) * s4dm_x -
+ 3 * (nobs - 1) * tmp)
+ output[i] /= tmp * (nobs - 2) * (nobs - 3)
+ else:
+ # multiplications are cheap, divisions and square roots are not
+ tmp = (nobs - 2) * (nobs - 2) * s2dm_x * s2dm_x * s2dm_x
+ output[i] = s3dm_x * nobs * sqrt((nobs - 1) / tmp)
return output
+
#-------------------------------------------------------------------------------
# Rolling median, min, max
diff --git a/pandas/stats/moments.py b/pandas/stats/moments.py
index 3cddae45e7516..f383660d1a709 100644
--- a/pandas/stats/moments.py
+++ b/pandas/stats/moments.py
@@ -355,7 +355,8 @@ def rolling_corr_pairwise(df1, df2=None, window=None, min_periods=None,
def _rolling_moment(arg, window, func, minp, axis=0, freq=None, center=False,
- how=None, args=(), kwargs={}, **kwds):
+ how=None, args=(), kwargs={}, center_data=False,
+ norm_data=False, **kwds):
"""
Rolling statistical measure using supplied function. Designed to be
used with passed-in Cython array-based functions.
@@ -378,6 +379,11 @@ def _rolling_moment(arg, window, func, minp, axis=0, freq=None, center=False,
Passed on to func
kwargs : dict
Passed on to func
+ center_data : bool
+ If True, subtract the mean of the data from the values
+ norm_data: bool
+ If True, subtract the mean of the data from the values, and divide
+ by their standard deviation.
Returns
-------
@@ -385,8 +391,9 @@ def _rolling_moment(arg, window, func, minp, axis=0, freq=None, center=False,
"""
arg = _conv_timerule(arg, freq, how)
- return_hook, values = _process_data_structure(arg)
-
+ return_hook, values = _process_data_structure(arg,
+ center_data=center_data,
+ norm_data=norm_data)
if values.size == 0:
result = values.copy()
else:
@@ -423,7 +430,8 @@ def _center_window(rs, window, axis):
return rs
-def _process_data_structure(arg, kill_inf=True):
+def _process_data_structure(arg, kill_inf=True, center_data=False,
+ norm_data=False):
if isinstance(arg, DataFrame):
return_hook = lambda v: type(arg)(v, index=arg.index,
columns=arg.columns)
@@ -438,9 +446,15 @@ def _process_data_structure(arg, kill_inf=True):
if not issubclass(values.dtype.type, float):
values = values.astype(float)
- if kill_inf:
+ if kill_inf or center_data or norm_data:
values = values.copy()
- values[np.isinf(values)] = np.NaN
+ mask = np.isfinite(values)
+ if kill_inf:
+ values[~mask] = np.NaN
+ if center_data or norm_data:
+ values -= np.mean(values[mask])
+ if norm_data:
+ values /= np.std(values[mask])
return return_hook, values
@@ -629,7 +643,8 @@ def _use_window(minp, window):
return minp
-def _rolling_func(func, desc, check_minp=_use_window, how=None, additional_kw=''):
+def _rolling_func(func, desc, check_minp=_use_window, how=None,
+ additional_kw='', center_data=False, norm_data=False):
if how is None:
how_arg_str = 'None'
else:
@@ -645,7 +660,8 @@ def call_cython(arg, window, minp, args=(), kwargs={}, **kwds):
minp = check_minp(minp, window)
return func(arg, window, minp, **kwds)
return _rolling_moment(arg, window, call_cython, min_periods, freq=freq,
- center=center, how=how, **kwargs)
+ center=center, how=how, center_data=center_data,
+ norm_data=norm_data, **kwargs)
return f
@@ -657,16 +673,24 @@ def call_cython(arg, window, minp, args=(), kwargs={}, **kwds):
how='median')
_ts_std = lambda *a, **kw: _zsqrt(algos.roll_var(*a, **kw))
+def _roll_skew(*args, **kwargs):
+ kwargs['kurt'] = False
+ return algos.roll_higher_moment(*args, **kwargs)
+def _roll_kurt(*args, **kwargs):
+ kwargs['kurt'] = True
+ return algos.roll_higher_moment(*args, **kwargs)
rolling_std = _rolling_func(_ts_std, 'Moving standard deviation.',
check_minp=_require_min_periods(1),
additional_kw=_ddof_kw)
rolling_var = _rolling_func(algos.roll_var, 'Moving variance.',
check_minp=_require_min_periods(1),
additional_kw=_ddof_kw)
-rolling_skew = _rolling_func(algos.roll_skew, 'Unbiased moving skewness.',
- check_minp=_require_min_periods(3))
-rolling_kurt = _rolling_func(algos.roll_kurt, 'Unbiased moving kurtosis.',
- check_minp=_require_min_periods(4))
+rolling_skew = _rolling_func(_roll_skew, 'Unbiased moving skewness.',
+ check_minp=_require_min_periods(3),
+ center_data=True, norm_data=False)
+rolling_kurt = _rolling_func(_roll_kurt, 'Unbiased moving kurtosis.',
+ check_minp=_require_min_periods(4),
+ center_data=True, norm_data=True)
def rolling_quantile(arg, window, quantile, min_periods=None, freq=None,
@@ -903,9 +927,9 @@ def call_cython(arg, window, minp, args=(), kwargs={}, **kwds):
expanding_var = _expanding_func(algos.roll_var, 'Expanding variance.',
check_minp=_require_min_periods(1),
additional_kw=_ddof_kw)
-expanding_skew = _expanding_func(algos.roll_skew, 'Unbiased expanding skewness.',
+expanding_skew = _expanding_func(_roll_skew, 'Unbiased expanding skewness.',
check_minp=_require_min_periods(3))
-expanding_kurt = _expanding_func(algos.roll_kurt, 'Unbiased expanding kurtosis.',
+expanding_kurt = _expanding_func(_roll_kurt, 'Unbiased expanding kurtosis.',
check_minp=_require_min_periods(4))
diff --git a/pandas/stats/tests/test_moments.py b/pandas/stats/tests/test_moments.py
index e2ed27156d2b5..4826cd7cfccb9 100644
--- a/pandas/stats/tests/test_moments.py
+++ b/pandas/stats/tests/test_moments.py
@@ -9,14 +9,19 @@
import numpy as np
from distutils.version import LooseVersion
-from pandas import Series, DataFrame, Panel, bdate_range, isnull, notnull, concat
+from pandas import (
+ Series, DataFrame, Panel, bdate_range, isnull, notnull, concat
+)
from pandas.util.testing import (
- assert_almost_equal, assert_series_equal, assert_frame_equal, assert_panel_equal, assert_index_equal
+ assert_almost_equal, assert_series_equal, assert_frame_equal,
+ assert_panel_equal, assert_index_equal
)
import pandas.core.datetools as datetools
import pandas.stats.moments as mom
import pandas.util.testing as tm
from pandas.compat import range, zip, PY3, StringIO
+from pandas.stats.moments import (_roll_skew, _roll_kurt, _rolling_func,
+ _require_min_periods)
N, K = 100, 10
@@ -425,6 +430,16 @@ def test_rolling_skew(self):
raise nose.SkipTest('no scipy')
self._check_moment_func(mom.rolling_skew,
lambda x: skew(x, bias=False))
+ # To test the algorithm stability we need the raw function, as
+ # rolling_skew centers the data
+ test_roll_skew = _rolling_func(_roll_skew, 'Test rolling_skew',
+ check_minp=_require_min_periods(3),
+ center_data=False, norm_data=False)
+ self._check_moment_func(test_roll_skew,
+ lambda x: skew(x, bias=False),
+ has_min_periods=True, has_center=False,
+ has_time_rule=False, test_stable=True)
+
def test_rolling_kurt(self):
try:
@@ -433,6 +448,15 @@ def test_rolling_kurt(self):
raise nose.SkipTest('no scipy')
self._check_moment_func(mom.rolling_kurt,
lambda x: kurtosis(x, bias=False))
+ # To test the algorithm stability we need the raw function, as
+ # rolling_kurt centers and normalizes the data
+ test_roll_kurt = _rolling_func(_roll_kurt, 'Test rolling_kurt',
+ check_minp=_require_min_periods(4),
+ center_data=False, norm_data=False)
+ self._check_moment_func(test_roll_kurt,
+ lambda x: kurtosis(x, bias=False),
+ has_min_periods=True, has_center=False,
+ has_time_rule=False, test_stable=True)
def test_fperr_robustness(self):
# TODO: remove this once python 2.5 out of picture
@@ -542,8 +566,8 @@ def _check_ndarray(self, func, static_comp, window=50,
if test_stable:
result = func(self.arr + 1e9, window)
- assert_almost_equal(result[-1],
- static_comp(self.arr[-50:] + 1e9))
+ assert_almost_equal(result[-1], static_comp(self.arr[-50:]),
+ check_less_precise=True)
# Test window larger than array, #7297
if test_window:
| Close #6929. Hat tip to @behzadnouri for the z-scores idea in #8270, and to @seth-p for the general structure of the code, separating removal and addition of observations.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8424 | 2014-09-30T03:26:27Z | 2016-01-02T23:17:41Z | null | 2023-05-11T01:12:41Z |
DOC: create text.rst with string methods (GH8416) | diff --git a/doc/source/10min.rst b/doc/source/10min.rst
index 10921c2a32ed5..c98f41973e1ee 100644
--- a/doc/source/10min.rst
+++ b/doc/source/10min.rst
@@ -433,7 +433,12 @@ See more at :ref:`Histogramming and Discretization <basics.discretization>`
String Methods
~~~~~~~~~~~~~~
-See more at :ref:`Vectorized String Methods <basics.string_methods>`
+Series is equipped with a set of string processing methods in the `str`
+attribute that make it easy to operate on each element of the array, as in the
+code snippet below. Note that pattern-matching in `str` generally uses `regular
+expressions <https://docs.python.org/2/library/re.html>`__ by default (and in
+some cases always uses them). See more at :ref:`Vectorized String Methods
+<text.string_methods>`.
.. ipython:: python
diff --git a/doc/source/api.rst b/doc/source/api.rst
index 8598bae5758c9..cce15685035d0 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -1410,7 +1410,7 @@ Computations / Descriptive Stats
GroupBy.mean
GroupBy.median
GroupBy.min
- GroupBy.nth
+ GroupBy.nth
GroupBy.ohlc
GroupBy.prod
GroupBy.size
diff --git a/doc/source/basics.rst b/doc/source/basics.rst
index d7ec2dc54522f..b32874f5ca7d8 100644
--- a/doc/source/basics.rst
+++ b/doc/source/basics.rst
@@ -1159,172 +1159,27 @@ The ``.dt`` accessor works for period and timedelta dtypes.
``Series.dt`` will raise a ``TypeError`` if you access with a non-datetimelike values
-.. _basics.string_methods:
-
Vectorized string methods
-------------------------
-Series is equipped (as of pandas 0.8.1) with a set of string processing methods
-that make it easy to operate on each element of the array. Perhaps most
-importantly, these methods exclude missing/NA values automatically. These are
-accessed via the Series's ``str`` attribute and generally have names matching
-the equivalent (scalar) build-in string methods:
-
-Splitting and Replacing Strings
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-.. ipython:: python
-
- s = Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
- s.str.lower()
- s.str.upper()
- s.str.len()
-
-Methods like ``split`` return a Series of lists:
-
-.. ipython:: python
-
- s2 = Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h'])
- s2.str.split('_')
-
-Elements in the split lists can be accessed using ``get`` or ``[]`` notation:
-
-.. ipython:: python
-
- s2.str.split('_').str.get(1)
- s2.str.split('_').str[1]
-
-Methods like ``replace`` and ``findall`` take regular expressions, too:
-
-.. ipython:: python
-
- s3 = Series(['A', 'B', 'C', 'Aaba', 'Baca',
- '', np.nan, 'CABA', 'dog', 'cat'])
- s3
- s3.str.replace('^.a|dog', 'XX-XX ', case=False)
-
-Extracting Substrings
-~~~~~~~~~~~~~~~~~~~~~
-
-The method ``extract`` (introduced in version 0.13) accepts regular expressions
-with match groups. Extracting a regular expression with one group returns
-a Series of strings.
-
-.. ipython:: python
-
- Series(['a1', 'b2', 'c3']).str.extract('[ab](\d)')
-
-Elements that do not match return ``NaN``. Extracting a regular expression
-with more than one group returns a DataFrame with one column per group.
-
-.. ipython:: python
-
- Series(['a1', 'b2', 'c3']).str.extract('([ab])(\d)')
-
-Elements that do not match return a row filled with ``NaN``.
-Thus, a Series of messy strings can be "converted" into a
-like-indexed Series or DataFrame of cleaned-up or more useful strings,
-without necessitating ``get()`` to access tuples or ``re.match`` objects.
+Series is equipped with a set of string processing methods that make it easy to
+operate on each element of the array. Perhaps most importantly, these methods
+exclude missing/NA values automatically. These are accessed via the Series's
+``str`` attribute and generally have names matching the equivalent (scalar)
+built-in string methods. For example:
-The results dtype always is object, even if no match is found and the result
-only contains ``NaN``.
+ .. ipython:: python
-Named groups like
+ s = Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
+ s.str.lower()
-.. ipython:: python
-
- Series(['a1', 'b2', 'c3']).str.extract('(?P<letter>[ab])(?P<digit>\d)')
-
-and optional groups like
-
-.. ipython:: python
-
- Series(['a1', 'b2', '3']).str.extract('(?P<letter>[ab])?(?P<digit>\d)')
-
-can also be used.
-
-Testing for Strings that Match or Contain a Pattern
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-You can check whether elements contain a pattern:
-
-.. ipython:: python
-
- pattern = r'[a-z][0-9]'
- Series(['1', '2', '3a', '3b', '03c']).str.contains(pattern)
-
-or match a pattern:
-
-
-.. ipython:: python
-
- Series(['1', '2', '3a', '3b', '03c']).str.match(pattern, as_indexer=True)
-
-The distinction between ``match`` and ``contains`` is strictness: ``match``
-relies on strict ``re.match``, while ``contains`` relies on ``re.search``.
-
-.. warning::
-
- In previous versions, ``match`` was for *extracting* groups,
- returning a not-so-convenient Series of tuples. The new method ``extract``
- (described in the previous section) is now preferred.
-
- This old, deprecated behavior of ``match`` is still the default. As
- demonstrated above, use the new behavior by setting ``as_indexer=True``.
- In this mode, ``match`` is analogous to ``contains``, returning a boolean
- Series. The new behavior will become the default behavior in a future
- release.
-
-Methods like ``match``, ``contains``, ``startswith``, and ``endswith`` take
- an extra ``na`` argument so missing values can be considered True or False:
-
-.. ipython:: python
-
- s4 = Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
- s4.str.contains('A', na=False)
-
-.. csv-table::
- :header: "Method", "Description"
- :widths: 20, 80
+Powerful pattern-matching methods are provided as well, but note that
+pattern-matching generally uses `regular expressions
+<https://docs.python.org/2/library/re.html>`__ by default (and in some cases
+always uses them).
- ``cat``,Concatenate strings
- ``split``,Split strings on delimiter
- ``get``,Index into each element (retrieve i-th element)
- ``join``,Join strings in each element of the Series with passed separator
- ``contains``,Return boolean array if each string contains pattern/regex
- ``replace``,Replace occurrences of pattern/regex with some other string
- ``repeat``,Duplicate values (``s.str.repeat(3)`` equivalent to ``x * 3``)
- ``pad``,"Add whitespace to left, right, or both sides of strings"
- ``center``,Equivalent to ``pad(side='both')``
- ``wrap``,Split long strings into lines with length less than a given width
- ``slice``,Slice each string in the Series
- ``slice_replace``,Replace slice in each string with passed value
- ``count``,Count occurrences of pattern
- ``startswith``,Equivalent to ``str.startswith(pat)`` for each element
- ``endswith``,Equivalent to ``str.endswith(pat)`` for each element
- ``findall``,Compute list of all occurrences of pattern/regex for each string
- ``match``,"Call ``re.match`` on each element, returning matched groups as list"
- ``extract``,"Call ``re.match`` on each element, as ``match`` does, but return matched groups as strings for convenience."
- ``len``,Compute string lengths
- ``strip``,Equivalent to ``str.strip``
- ``rstrip``,Equivalent to ``str.rstrip``
- ``lstrip``,Equivalent to ``str.lstrip``
- ``lower``,Equivalent to ``str.lower``
- ``upper``,Equivalent to ``str.upper``
-
-
-Getting indicator variables from separated strings
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-You can extract dummy variables from string columns.
-For example if they are separated by a ``'|'``:
-
- .. ipython:: python
-
- s = pd.Series(['a', 'a|b', np.nan, 'a|c'])
- s.str.get_dummies(sep='|')
-
-See also :func:`~pandas.get_dummies`.
+Please see :ref:`Vectorized String Methods <text.string_methods>` for a complete
+description.
.. _basics.sorting:
diff --git a/doc/source/index.rst.template b/doc/source/index.rst.template
index 1b692a317051d..ccedaaa0429f0 100644
--- a/doc/source/index.rst.template
+++ b/doc/source/index.rst.template
@@ -122,6 +122,7 @@ See the package overview for more detail about what's in the library.
cookbook
dsintro
basics
+ text
options
indexing
advanced
diff --git a/doc/source/text.rst b/doc/source/text.rst
new file mode 100644
index 0000000000000..7032f5ff648a7
--- /dev/null
+++ b/doc/source/text.rst
@@ -0,0 +1,230 @@
+.. currentmodule:: pandas
+.. _text:
+
+.. ipython:: python
+ :suppress:
+
+ import numpy as np
+ from pandas import *
+ randn = np.random.randn
+ np.set_printoptions(precision=4, suppress=True)
+ from pandas.compat import lrange
+ options.display.max_rows=15
+
+======================
+Working with Text Data
+======================
+
+.. _text.string_methods:
+
+Series is equipped with a set of string processing methods
+that make it easy to operate on each element of the array. Perhaps most
+importantly, these methods exclude missing/NA values automatically. These are
+accessed via the Series's ``str`` attribute and generally have names matching
+the equivalent (scalar) built-in string methods:
+
+.. ipython:: python
+
+ s = Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
+ s.str.lower()
+ s.str.upper()
+ s.str.len()
+
+Splitting and Replacing Strings
+-------------------------------
+
+.. _text.split:
+
+Methods like ``split`` return a Series of lists:
+
+.. ipython:: python
+
+ s2 = Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h'])
+ s2.str.split('_')
+
+Easy to expand this to return a DataFrame
+
+.. ipython:: python
+
+ s2.str.split('_').apply(Series)
+
+Elements in the split lists can be accessed using ``get`` or ``[]`` notation:
+
+.. ipython:: python
+
+ s2.str.split('_').str.get(1)
+ s2.str.split('_').str[1]
+
+Methods like ``replace`` and ``findall`` take `regular expressions
+<https://docs.python.org/2/library/re.html>`__, too:
+
+.. ipython:: python
+
+ s3 = Series(['A', 'B', 'C', 'Aaba', 'Baca',
+ '', np.nan, 'CABA', 'dog', 'cat'])
+ s3
+ s3.str.replace('^.a|dog', 'XX-XX ', case=False)
+
+Some caution must be taken to keep regular expressions in mind! For example, the
+following code will cause trouble because of the regular expression meaning of
+`$`:
+
+.. ipython:: python
+
+ # Consider the following badly formatted financial data
+ dollars = Series(['12', '-$10', '$10,000'])
+
+ # This does what you'd naively expect:
+ dollars.str.replace('$', '')
+
+ # But this doesn't:
+ dollars.str.replace('-$', '-')
+
+ # We need to escape the special character (for >1 len patterns)
+ dollars.str.replace(r'-\$', '-')
+
+Indexing with ``.str``
+----------------------
+
+.. _text.indexing:
+
+You can use ``[]`` notation to directly index by position locations. If you index past the end
+of the string, the result will be a ``NaN``.
+
+
+.. ipython:: python
+
+ s = Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan,
+ 'CABA', 'dog', 'cat'])
+
+ s.str[0]
+ s.str[1]
+
+Extracting Substrings
+---------------------
+
+.. _text.extract:
+
+The method ``extract`` (introduced in version 0.13) accepts `regular expressions
+<https://docs.python.org/2/library/re.html>`__ with match groups. Extracting a
+regular expression with one group returns a Series of strings.
+
+.. ipython:: python
+
+ Series(['a1', 'b2', 'c3']).str.extract('[ab](\d)')
+
+Elements that do not match return ``NaN``. Extracting a regular expression
+with more than one group returns a DataFrame with one column per group.
+
+.. ipython:: python
+
+ Series(['a1', 'b2', 'c3']).str.extract('([ab])(\d)')
+
+Elements that do not match return a row filled with ``NaN``.
+Thus, a Series of messy strings can be "converted" into a
+like-indexed Series or DataFrame of cleaned-up or more useful strings,
+without necessitating ``get()`` to access tuples or ``re.match`` objects.
+
+The results dtype always is object, even if no match is found and the result
+only contains ``NaN``.
+
+Named groups like
+
+.. ipython:: python
+
+ Series(['a1', 'b2', 'c3']).str.extract('(?P<letter>[ab])(?P<digit>\d)')
+
+and optional groups like
+
+.. ipython:: python
+
+ Series(['a1', 'b2', '3']).str.extract('(?P<letter>[ab])?(?P<digit>\d)')
+
+can also be used.
+
+Testing for Strings that Match or Contain a Pattern
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+You can check whether elements contain a pattern:
+
+.. ipython:: python
+
+ pattern = r'[a-z][0-9]'
+ Series(['1', '2', '3a', '3b', '03c']).str.contains(pattern)
+
+or match a pattern:
+
+
+.. ipython:: python
+
+ Series(['1', '2', '3a', '3b', '03c']).str.match(pattern, as_indexer=True)
+
+The distinction between ``match`` and ``contains`` is strictness: ``match``
+relies on strict ``re.match``, while ``contains`` relies on ``re.search``.
+
+.. warning::
+
+ In previous versions, ``match`` was for *extracting* groups,
+ returning a not-so-convenient Series of tuples. The new method ``extract``
+ (described in the previous section) is now preferred.
+
+ This old, deprecated behavior of ``match`` is still the default. As
+ demonstrated above, use the new behavior by setting ``as_indexer=True``.
+ In this mode, ``match`` is analogous to ``contains``, returning a boolean
+ Series. The new behavior will become the default behavior in a future
+ release.
+
+Methods like ``match``, ``contains``, ``startswith``, and ``endswith`` take
+ an extra ``na`` argument so missing values can be considered True or False:
+
+.. ipython:: python
+
+ s4 = Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
+ s4.str.contains('A', na=False)
+
+Creating Indicator Variables
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+You can extract dummy variables from string columns.
+For example if they are separated by a ``'|'``:
+
+ .. ipython:: python
+
+ s = Series(['a', 'a|b', np.nan, 'a|c'])
+ s.str.get_dummies(sep='|')
+
+See also :func:`~pandas.get_dummies`.
+
+Method Summary
+--------------
+
+.. _text.summary:
+
+.. csv-table::
+ :header: "Method", "Description"
+ :widths: 20, 80
+
+ :meth:`~core.strings.StringMethods.cat`,Concatenate strings
+ :meth:`~core.strings.StringMethods.split`,Split strings on delimiter
+ :meth:`~core.strings.StringMethods.get`,Index into each element (retrieve i-th element)
+ :meth:`~core.strings.StringMethods.join`,Join strings in each element of the Series with passed separator
+ :meth:`~core.strings.StringMethods.contains`,Return boolean array if each string contains pattern/regex
+ :meth:`~core.strings.StringMethods.replace`,Replace occurrences of pattern/regex with some other string
+ :meth:`~core.strings.StringMethods.repeat`,Duplicate values (``s.str.repeat(3)`` equivalent to ``x * 3``)
+ :meth:`~core.strings.StringMethods.pad`,"Add whitespace to left, right, or both sides of strings"
+ :meth:`~core.strings.StringMethods.center`,Equivalent to ``pad(side='both')``
+ :meth:`~core.strings.StringMethods.wrap`,Split long strings into lines with length less than a given width
+ :meth:`~core.strings.StringMethods.slice`,Slice each string in the Series
+ :meth:`~core.strings.StringMethods.slice_replace`,Replace slice in each string with passed value
+ :meth:`~core.strings.StringMethods.count`,Count occurrences of pattern
+ :meth:`~core.strings.StringMethods.startswith`,Equivalent to ``str.startswith(pat)`` for each element
+ :meth:`~core.strings.StringMethods.endswith`,Equivalent to ``str.endswith(pat)`` for each element
+ :meth:`~core.strings.StringMethods.findall`,Compute list of all occurrences of pattern/regex for each string
+ :meth:`~core.strings.StringMethods.match`,"Call ``re.match`` on each element, returning matched groups as list"
+ :meth:`~core.strings.StringMethods.extract`,"Call ``re.match`` on each element, as ``match`` does, but return matched groups as strings for convenience."
+ :meth:`~core.strings.StringMethods.len`,Compute string lengths
+ :meth:`~core.strings.StringMethods.strip`,Equivalent to ``str.strip``
+ :meth:`~core.strings.StringMethods.rstrip`,Equivalent to ``str.rstrip``
+ :meth:`~core.strings.StringMethods.lstrip`,Equivalent to ``str.lstrip``
+ :meth:`~core.strings.StringMethods.lower`,Equivalent to ``str.lower``
+ :meth:`~core.strings.StringMethods.upper`,Equivalent to ``str.upper``
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index fcf928a975c2b..43e98b161732f 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -19,6 +19,7 @@ users upgrade to this version.
- New scalar type ``Timedelta``, and a new index type ``TimedeltaIndex``, see :ref:`here <whatsnew_0150.timedeltaindex>`
- New datetimelike properties accessor ``.dt`` for Series, see :ref:`Datetimelike Properties <whatsnew_0150.dt>`
- Split indexing documentation into :ref:`Indexing and Selecting Data <indexing>` and :ref:`MultiIndex / Advanced Indexing <advanced>`
+ - Split out string methods documentation into :ref:`Working with Text Data <text>`
- ``read_csv`` will now by default ignore blank lines when parsing, see :ref:`here <whatsnew_0150.blanklines>`
- API change in using Indexes in set operations, see :ref:`here <whatsnew_0150.index_set_ops>`
- Internal refactoring of the ``Index`` class to no longer sub-class ``ndarray``, see :ref:`Internal Refactoring <whatsnew_0150.refactoring>`
diff --git a/doc/source/v0.8.1.txt b/doc/source/v0.8.1.txt
index cecf6f16cdc71..8227bc6bc9c66 100644
--- a/doc/source/v0.8.1.txt
+++ b/doc/source/v0.8.1.txt
@@ -10,7 +10,7 @@ processing functionality and a series of new plot types and options.
New features
~~~~~~~~~~~~
- - Add :ref:`vectorized string processing methods <basics.string_methods>`
+ - Add :ref:`vectorized string processing methods <text.string_methods>`
accessible via Series.str (:issue:`620`)
- Add option to disable adjustment in EWMA (:issue:`1584`)
- :ref:`Radviz plot <visualization.radviz>` (:issue:`1566`)
diff --git a/doc/source/v0.9.0.txt b/doc/source/v0.9.0.txt
index 2b385a7e7b8f0..b60fb9cc64f4a 100644
--- a/doc/source/v0.9.0.txt
+++ b/doc/source/v0.9.0.txt
@@ -18,7 +18,7 @@ New features
~~~~~~~~~~~~
- Add ``encode`` and ``decode`` for unicode handling to :ref:`vectorized
- string processing methods <basics.string_methods>` in Series.str (:issue:`1706`)
+ string processing methods <text.string_methods>` in Series.str (:issue:`1706`)
- Add ``DataFrame.to_latex`` method (:issue:`1735`)
- Add convenient expanding window equivalents of all rolling_* ops (:issue:`1785`)
- Add Options class to pandas.io.data for fetching options data from Yahoo!
| closes #8416
| https://api.github.com/repos/pandas-dev/pandas/pulls/8423 | 2014-09-29T21:51:15Z | 2014-09-30T14:10:34Z | 2014-09-30T14:10:34Z | 2014-09-30T14:10:34Z |
FIX: Add Categorical.searchsorted stub | diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index d404601bcafa1..d2708890c5ec2 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -726,6 +726,9 @@ def T(self):
def nbytes(self):
return self._codes.nbytes + self._categories.values.nbytes
+ def searchsorted(self, v, side='left', sorter=None):
+ raise NotImplementedError("See https://github.com/pydata/pandas/issues/8420")
+
def isnull(self):
"""
Detect missing values
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index d4cf687486cfb..e05d7285592aa 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -889,6 +889,15 @@ def test_nbytes(self):
exp = cat._codes.nbytes + cat._categories.values.nbytes
self.assertEqual(cat.nbytes, exp)
+ def test_searchsorted(self):
+
+ # See https://github.com/pydata/pandas/issues/8420
+ # TODO: implement me...
+ cat = pd.Categorical([1,2,3])
+ def f():
+ cat.searchsorted(3)
+ self.assertRaises(NotImplementedError, f)
+
def test_deprecated_labels(self):
# TODO: labels is deprecated and should be removed in 0.18 or 2017, whatever is earlier
cat = pd.Categorical([1,2,3, np.nan], categories=[1,2,3])
| For https://github.com/pydata/pandas/pull/7447, add a searchsorted
stub, which simple raises `NotImplementedError`, so that we raise a
more clear error than attribute not found.
xref #8420
| https://api.github.com/repos/pandas-dev/pandas/pulls/8421 | 2014-09-29T18:06:20Z | 2014-09-29T20:52:02Z | 2014-09-29T20:52:02Z | 2014-09-29T20:52:03Z |
Moved startup script information to options docs and fixed link | diff --git a/doc/source/faq.rst b/doc/source/faq.rst
index 6aa51346f008a..a613d53218ce2 100644
--- a/doc/source/faq.rst
+++ b/doc/source/faq.rst
@@ -65,28 +65,6 @@ Monkey-patching existing methods is usually a bad idea in that respect.
When used with proper care, however, it's a very useful tool to have.
-.. _ref-python-startup:
-
-Setting startup options for pandas in python/ipython environment
-----------------------------------------------------------------
-
-Using startup scripts for the python/ipython environment to import pandas and set options makes working with pandas more efficient. To do this, create a .py or .ipy script in the startup directory of the desired profile. An example where the startup folder is in a default ipython profile can be found at:
-
-.. code-block:: python
-
- $IPYTHONDIR/profile_default/startup
-
-More information can be found in the `ipython profile documentation
-<http://ipython.org/ipython-doc/1/config/overview.html>`__. An example startup script for pandas is displayed below:
-
-.. code-block:: python
-
- import pandas as pd
- pd.set_option('display.max_rows', 999)
- pd.set_option('precision', 5)
-
-For a list of options available for pandas, see the :ref:`pandas options documentation <options>`.
-
.. _ref-scikits-migration:
Migrating from scikits.timeseries to pandas >= 0.8.0
diff --git a/doc/source/options.rst b/doc/source/options.rst
index 420e4f20261ca..95a137fb96e66 100644
--- a/doc/source/options.rst
+++ b/doc/source/options.rst
@@ -124,6 +124,25 @@ are restored automatically when you exit the `with` block:
print(pd.get_option("display.max_columns"))
+Setting Startup Options in python/ipython Environment
+-----------------------------------------------------
+
+Using startup scripts for the python/ipython environment to import pandas and set options makes working with pandas more efficient. To do this, create a .py or .ipy script in the startup directory of the desired profile. An example where the startup folder is in a default ipython profile can be found at:
+
+.. code-block:: python
+
+ $IPYTHONDIR/profile_default/startup
+
+More information can be found in the `ipython documentation
+<http://ipython.org/ipython-doc/stable/interactive/tutorial.html#startup-files>`__. An example startup script for pandas is displayed below:
+
+.. code-block:: python
+
+ import pandas as pd
+ pd.set_option('display.max_rows', 999)
+ pd.set_option('precision', 5)
+
+
Frequently Used Options
-----------------------
The following is a walkthrough of the more frequently used display options.
| based on #8407 and #5748
| https://api.github.com/repos/pandas-dev/pandas/pulls/8418 | 2014-09-29T16:21:27Z | 2014-09-29T20:55:13Z | 2014-09-29T20:55:13Z | 2014-09-29T20:55:23Z |
BUG: regression in groupby with a pass thru multiindex on axis=1 (GH7997) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 225c779071153..22860a143476e 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -549,7 +549,7 @@ Internal Refactoring
In 0.15.0 ``Index`` has internally been refactored to no longer sub-class ``ndarray``
but instead subclass ``PandasObject``, similarly to the rest of the pandas objects. This change allows very easy sub-classing and creation of new index types. This should be
-a transparent change with only very limited API implications (:issue:`5080`, :issue:`7439`, :issue:`7796`, :issue:`8024`, :issue:`8367`)
+a transparent change with only very limited API implications (:issue:`5080`, :issue:`7439`, :issue:`7796`, :issue:`8024`, :issue:`8367`, :issue:`7997`)
- you may need to unpickle pandas version < 0.15.0 pickles using ``pd.read_pickle`` rather than ``pickle.load``. See :ref:`pickle docs <io.pickle>`
- when plotting with a ``PeriodIndex``. The ``matplotlib`` internal axes will now be arrays of ``Period`` rather than a ``PeriodIndex``. (this is similar to how a ``DatetimeIndex`` passes arrays of ``datetimes`` now)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index db04f4933d5aa..9698d91b3ed8a 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -3233,7 +3233,8 @@ def _reindex_output(self, result):
levels_list = [ ping._group_index for ping in groupings ]
index = MultiIndex.from_product(levels_list, names=self.grouper.names)
- return result.reindex(**{ self.obj._get_axis_name(self.axis) : index, 'copy' : False }).sortlevel()
+ d = { self.obj._get_axis_name(self.axis) : index, 'copy' : False }
+ return result.reindex(**d).sortlevel(axis=self.axis)
def _iterate_column_groupbys(self):
for i, colname in enumerate(self._selected_obj.columns):
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index c6b5ff1769591..3fdd7c3459c74 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -1495,6 +1495,16 @@ def test_groupby_as_index_agg(self):
result3 = grouped['C'].agg({'Q': np.sum})
assert_frame_equal(result3, expected3)
+ def test_mulitindex_passthru(self):
+
+ # GH 7997
+ # regression from 0.14.1
+ df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
+ df.columns = pd.MultiIndex.from_tuples([(0,1),(1,1),(2,1)])
+
+ result = df.groupby(axis=1, level=[0,1]).first()
+ assert_frame_equal(result, df)
+
def test_multifunc_select_col_integer_cols(self):
df = self.df
df.columns = np.arange(len(df.columns))
| closes #7997
| https://api.github.com/repos/pandas-dev/pandas/pulls/8417 | 2014-09-29T15:51:59Z | 2014-09-30T19:39:45Z | 2014-09-30T19:39:45Z | 2014-09-30T19:39:45Z |
API/BUG: a UTC object inserted into a Series/DataFrame will preserve the UTC and be object dtype (GH8411) | diff --git a/doc/source/basics.rst b/doc/source/basics.rst
index 985cd22c03382..d7ec2dc54522f 100644
--- a/doc/source/basics.rst
+++ b/doc/source/basics.rst
@@ -1130,6 +1130,12 @@ You can easily produces tz aware transformations:
stz
stz.dt.tz
+You can also chain these types of operations:
+
+.. ipython:: python
+
+ s.dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
+
The ``.dt`` accessor works for period and timedelta dtypes.
.. ipython:: python
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 988acc24b686e..442919928e3e8 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -26,7 +26,11 @@ users upgrade to this version.
- :ref:`Other Enhancements <whatsnew_0150.enhancements>`
-- :ref:`API Changes <whatsnew_0150.api>`, and :ref:`Rolling/Expanding Moments API Changes <whatsnew_0150.roll>`
+- :ref:`API Changes <whatsnew_0150.api>`
+
+- :ref:`Timezone API Change <whatsnew_0150.tz>`
+
+- :ref:`Rolling/Expanding Moments API Changes <whatsnew_0150.roll>`
- :ref:`Performance Improvements <whatsnew_0150.performance>`
@@ -137,27 +141,6 @@ API changes
In [3]: idx.isin(['a', 'c', 'e'], level=1)
Out[3]: array([ True, False, True, True, False, True], dtype=bool)
-- ``tz_localize(None)`` for tz-aware ``Timestamp`` and ``DatetimeIndex`` now removes timezone holding local time,
- previously results in ``Exception`` or ``TypeError`` (:issue:`7812`)
-
- .. ipython:: python
-
- ts = Timestamp('2014-08-01 09:00', tz='US/Eastern')
- ts
- ts.tz_localize(None)
-
- didx = DatetimeIndex(start='2014-08-01 09:00', freq='H', periods=10, tz='US/Eastern')
- didx
- didx.tz_localize(None)
-
-- ``tz_localize`` now accepts the ``ambiguous`` keyword which allows for passing an array of bools
- indicating whether the date belongs in DST or not, 'NaT' for setting transition times to NaT,
- 'infer' for inferring DST/non-DST, and 'raise' (default) for an AmbiguousTimeError to be raised. See :ref:`the docs<timeseries.timezone_ambiguous>` for more details (:issue:`7943`)
-
-- ``DataFrame.tz_localize`` and ``DataFrame.tz_convert`` now accepts an optional ``level`` argument
- for localizing a specific level of a MultiIndex (:issue:`7846`)
-- ``Timestamp.tz_localize`` and ``Timestamp.tz_convert`` now raise ``TypeError`` in error cases, rather than ``Exception`` (:issue:`8025`)
-- ``Timestamp.__repr__`` displays ``dateutil.tz.tzoffset`` info (:issue:`7907`)
- ``merge``, ``DataFrame.merge``, and ``ordered_merge`` now return the same type
as the ``left`` argument. (:issue:`7737`)
@@ -305,6 +288,12 @@ You can easily produce tz aware transformations:
stz
stz.dt.tz
+You can also chain these types of operations:
+
+.. ipython:: python
+
+ s.dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
+
The ``.dt`` accessor works for period and timedelta dtypes.
.. ipython:: python
@@ -324,6 +313,37 @@ The ``.dt`` accessor works for period and timedelta dtypes.
s.dt.seconds
s.dt.components
+.. _whatsnew_0150.tz:
+
+Timezone API changes
+~~~~~~~~~~~~~~~~~~~~
+
+- ``tz_localize(None)`` for tz-aware ``Timestamp`` and ``DatetimeIndex`` now removes timezone holding local time,
+ previously this resulted in ``Exception`` or ``TypeError`` (:issue:`7812`)
+
+ .. ipython:: python
+
+ ts = Timestamp('2014-08-01 09:00', tz='US/Eastern')
+ ts
+ ts.tz_localize(None)
+
+ didx = DatetimeIndex(start='2014-08-01 09:00', freq='H', periods=10, tz='US/Eastern')
+ didx
+ didx.tz_localize(None)
+
+- ``tz_localize`` now accepts the ``ambiguous`` keyword which allows for passing an array of bools
+ indicating whether the date belongs in DST or not, 'NaT' for setting transition times to NaT,
+ 'infer' for inferring DST/non-DST, and 'raise' (default) for an AmbiguousTimeError to be raised. See :ref:`the docs<timeseries.timezone_ambiguous>` for more details (:issue:`7943`)
+
+- ``DataFrame.tz_localize`` and ``DataFrame.tz_convert`` now accepts an optional ``level`` argument
+ for localizing a specific level of a MultiIndex (:issue:`7846`)
+
+- ``Timestamp.tz_localize`` and ``Timestamp.tz_convert`` now raise ``TypeError`` in error cases, rather than ``Exception`` (:issue:`8025`)
+
+- a timeseries/index localized to UTC when inserted into a Series/DataFrame will preserve the UTC timezone (rather than being a naive ``datetime64[ns]``) as ``object`` dtype (:issue:`8411`)
+
+- ``Timestamp.__repr__`` displays ``dateutil.tz.tzoffset`` info (:issue:`7907`)
+
.. _whatsnew_0150.roll:
Rolling/Expanding Moments API changes
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 9402d9a6d0685..223cb4fe78e94 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -26,7 +26,7 @@
from pandas.core.common import (isnull, notnull, PandasError, _try_sort,
_default_index, _maybe_upcast, _is_sequence,
_infer_dtype_from_scalar, _values_from_object,
- is_list_like, _get_dtype)
+ is_list_like, _get_dtype, _maybe_box_datetimelike)
from pandas.core.generic import NDFrame, _shared_docs
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas.core.indexing import (_maybe_droplevels,
@@ -1539,7 +1539,7 @@ def get_value(self, index, col, takeable=False):
if takeable:
series = self._iget_item_cache(col)
- return series.values[index]
+ return _maybe_box_datetimelike(series.values[index])
series = self._get_item_cache(col)
engine = self.index._engine
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 80d81f4e283f3..700eb8591fdf9 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -3528,7 +3528,7 @@ def test_column_dups_indexing2(self):
# GH 8363
# datetime ops with a non-unique index
- df = DataFrame({'A' : np.arange(5,dtype='int64'),
+ df = DataFrame({'A' : np.arange(5,dtype='int64'),
'B' : np.arange(1,6,dtype='int64')},
index=[2,2,3,3,4])
result = df.B-df.A
@@ -3654,6 +3654,18 @@ def test_constructor_with_datetimes(self):
self.assertEqual(df.iat[0,0],dt)
assert_series_equal(df.dtypes,Series({'End Date' : np.dtype('object') }))
+ # tz-aware (UTC and other tz's)
+ # GH 8411
+ dr = date_range('20130101',periods=3)
+ df = DataFrame({ 'value' : dr})
+ self.assertTrue(df.iat[0,0].tz is None)
+ dr = date_range('20130101',periods=3,tz='UTC')
+ df = DataFrame({ 'value' : dr})
+ self.assertTrue(str(df.iat[0,0].tz) == 'UTC')
+ dr = date_range('20130101',periods=3,tz='US/Eastern')
+ df = DataFrame({ 'value' : dr})
+ self.assertTrue(str(df.iat[0,0].tz) == 'US/Eastern')
+
# GH 7822
# preserver an index with a tz on dict construction
i = date_range('1/1/2011', periods=5, freq='10s', tz = 'US/Eastern')
@@ -7654,7 +7666,7 @@ def test_fillna_dataframe(self):
index = list('VWXYZ'))
assert_frame_equal(result, expected)
-
+
def test_fillna_columns(self):
df = DataFrame(np.random.randn(10, 10))
df.values[:, ::2] = np.nan
@@ -12791,8 +12803,8 @@ def test_consolidate_datetime64(self):
df.starting = ser_starting.index
df.ending = ser_ending.index
- assert_array_equal(df.starting.values, ser_starting.index.values)
- assert_array_equal(df.ending.values, ser_ending.index.values)
+ tm.assert_index_equal(pd.DatetimeIndex(df.starting), ser_starting.index)
+ tm.assert_index_equal(pd.DatetimeIndex(df.ending), ser_ending.index)
def _check_bool_op(self, name, alternative, frame=None, has_skipna=True,
has_bool_only=False):
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 0b863f9662e14..60b99ff28da55 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -135,6 +135,11 @@ def compare(s, name):
freq_result = s.dt.freq
self.assertEqual(freq_result, DatetimeIndex(s.values, freq='infer').freq)
+ # let's localize, then convert
+ result = s.dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
+ expected = Series(DatetimeIndex(s.values).tz_localize('UTC').tz_convert('US/Eastern'),index=s.index)
+ tm.assert_series_equal(result, expected)
+
# timedeltaindex
for s in [Series(timedelta_range('1 day',periods=5)),
Series(timedelta_range('1 day 01:23:45',periods=5,freq='s')),
@@ -810,6 +815,15 @@ def test_constructor_dtype_datetime64(self):
s = Series([pd.NaT, np.nan, '2013-08-05 15:30:00.000001'])
self.assertEqual(s.dtype,'datetime64[ns]')
+ # tz-aware (UTC and other tz's)
+ # GH 8411
+ dr = date_range('20130101',periods=3)
+ self.assertTrue(Series(dr).iloc[0].tz is None)
+ dr = date_range('20130101',periods=3,tz='UTC')
+ self.assertTrue(str(Series(dr).iloc[0].tz) == 'UTC')
+ dr = date_range('20130101',periods=3,tz='US/Eastern')
+ self.assertTrue(str(Series(dr).iloc[0].tz) == 'US/Eastern')
+
def test_constructor_periodindex(self):
# GH7932
# converting a PeriodIndex when put in a Series
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 8e39d3b3966e1..2483e0ebb32a5 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -744,7 +744,7 @@ def _to_embed(self, keep_tz=False):
This is for internal compat
"""
- if keep_tz and self.tz is not None and str(self.tz) != 'UTC':
+ if keep_tz and self.tz is not None:
return self.asobject.values
return self.values
| closes #8411
| https://api.github.com/repos/pandas-dev/pandas/pulls/8415 | 2014-09-29T14:03:46Z | 2014-09-29T21:43:23Z | 2014-09-29T21:43:23Z | 2014-09-29T21:46:17Z |
FIX: add nbytes property in Categorical | diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index ef14897cdbc90..d404601bcafa1 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -722,6 +722,10 @@ def __array__(self, dtype=None):
def T(self):
return self
+ @property
+ def nbytes(self):
+ return self._codes.nbytes + self._categories.values.nbytes
+
def isnull(self):
"""
Detect missing values
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index edf18edd6a20d..d4cf687486cfb 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -884,6 +884,11 @@ def test_set_item_nan(self):
exp = np.array([0,1,3,2])
self.assert_numpy_array_equal(cat.codes, exp)
+ def test_nbytes(self):
+ cat = pd.Categorical([1,2,3])
+ exp = cat._codes.nbytes + cat._categories.values.nbytes
+ self.assertEqual(cat.nbytes, exp)
+
def test_deprecated_labels(self):
# TODO: labels is deprecated and should be removed in 0.18 or 2017, whatever is earlier
cat = pd.Categorical([1,2,3, np.nan], categories=[1,2,3])
| Contribution to https://github.com/pydata/pandas/pull/7619
| https://api.github.com/repos/pandas-dev/pandas/pulls/8414 | 2014-09-29T13:14:15Z | 2014-09-29T14:05:45Z | 2014-09-29T14:05:45Z | 2014-09-29T14:05:50Z |
Categorical doc fixups | diff --git a/doc/source/10min.rst b/doc/source/10min.rst
index 6320be3920730..10921c2a32ed5 100644
--- a/doc/source/10min.rst
+++ b/doc/source/10min.rst
@@ -640,27 +640,44 @@ Categoricals
------------
Since version 0.15, pandas can include categorical data in a ``DataFrame``. For full docs, see the
-:ref:`Categorical introduction <categorical>` and the :ref:`API documentation <api.categorical>` .
+:ref:`categorical introduction <categorical>` and the :ref:`API documentation <api.categorical>`.
.. ipython:: python
df = pd.DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']})
- # convert the raw grades to a categorical
- df["grade"] = pd.Categorical(df["raw_grade"])
+Convert the raw grades to a categorical data type.
- # Alternative: df["grade"] = df["raw_grade"].astype("category")
+.. ipython:: python
+
+ df["grade"] = df["raw_grade"].astype("category")
df["grade"]
- # Rename the categories inplace
+Rename the categories to more meaningful names (assigning to ``Series.cat.categories`` is inplace!)
+
+.. ipython:: python
+
df["grade"].cat.categories = ["very good", "good", "very bad"]
- # Reorder the categories and simultaneously add the missing categories
+Reorder the categories and simultaneously add the missing categories (methods under ``Series
+.cat`` return a new ``Series`` per default).
+
+.. ipython:: python
+
df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium", "good", "very good"])
df["grade"]
+
+Sorting is per order in the categories, not lexical order.
+
+.. ipython:: python
+
df.sort("grade")
- df.groupby("grade").size()
+Grouping by a categorical column shows also empty categories.
+
+.. ipython:: python
+
+ df.groupby("grade").size()
Plotting
diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst
index a4e97a6e8d17c..669a39d437a34 100644
--- a/doc/source/categorical.rst
+++ b/doc/source/categorical.rst
@@ -611,6 +611,8 @@ available ("missing value") or `np.nan` is a valid category.
pd.isnull(s)
s.fillna("a")
+.. _categorical.rfactor:
+
Differences to R's `factor`
---------------------------
diff --git a/doc/source/comparison_with_r.rst b/doc/source/comparison_with_r.rst
index 84bba77e0dfa3..89c46d21c56a2 100644
--- a/doc/source/comparison_with_r.rst
+++ b/doc/source/comparison_with_r.rst
@@ -6,7 +6,7 @@
import pandas as pd
import numpy as np
- options.display.max_rows=15
+ pd.options.display.max_rows=15
Comparison with R / R libraries
*******************************
@@ -51,7 +51,7 @@ Selecting multiple columns by name in ``pandas`` is straightforward
.. ipython:: python
- df = DataFrame(np.random.randn(10, 3), columns=list('abc'))
+ df = pd.DataFrame(np.random.randn(10, 3), columns=list('abc'))
df[['a', 'c']]
df.loc[:, ['a', 'c']]
@@ -63,7 +63,7 @@ with a combination of the ``iloc`` indexer attribute and ``numpy.r_``.
named = list('abcdefg')
n = 30
columns = named + np.arange(len(named), n).tolist()
- df = DataFrame(np.random.randn(n, n), columns=columns)
+ df = pd.DataFrame(np.random.randn(n, n), columns=columns)
df.iloc[:, np.r_[:10, 24:30]]
@@ -88,8 +88,7 @@ function.
.. ipython:: python
- from pandas import DataFrame
- df = DataFrame({
+ df = pd.DataFrame({
'v1': [1,3,5,7,8,3,5,np.nan,4,5,7,9],
'v2': [11,33,55,77,88,33,55,np.nan,44,55,77,99],
'by1': ["red", "blue", 1, 2, np.nan, "big", 1, 2, "red", 1, np.nan, 12],
@@ -166,7 +165,7 @@ In ``pandas`` we may use :meth:`~pandas.pivot_table` method to handle this:
import random
import string
- baseball = DataFrame({
+ baseball = pd.DataFrame({
'team': ["team %d" % (x+1) for x in range(5)]*5,
'player': random.sample(list(string.ascii_lowercase),25),
'batting avg': np.random.uniform(.200, .400, 25)
@@ -197,7 +196,7 @@ index/slice as well as standard boolean indexing:
.. ipython:: python
- df = DataFrame({'a': np.random.randn(10), 'b': np.random.randn(10)})
+ df = pd.DataFrame({'a': np.random.randn(10), 'b': np.random.randn(10)})
df.query('a <= b')
df[df.a <= df.b]
df.loc[df.a <= df.b]
@@ -225,7 +224,7 @@ In ``pandas`` the equivalent expression, using the
.. ipython:: python
- df = DataFrame({'a': np.random.randn(10), 'b': np.random.randn(10)})
+ df = pd.DataFrame({'a': np.random.randn(10), 'b': np.random.randn(10)})
df.eval('a + b')
df.a + df.b # same as the previous expression
@@ -283,7 +282,7 @@ In ``pandas`` the equivalent expression, using the
.. ipython:: python
- df = DataFrame({
+ df = pd.DataFrame({
'x': np.random.uniform(1., 168., 120),
'y': np.random.uniform(7., 334., 120),
'z': np.random.uniform(1.7, 20.7, 120),
@@ -317,7 +316,7 @@ In Python, since ``a`` is a list, you can simply use list comprehension.
.. ipython:: python
a = np.array(list(range(1,24))+[np.NAN]).reshape(2,3,4)
- DataFrame([tuple(list(x)+[val]) for x, val in np.ndenumerate(a)])
+ pd.DataFrame([tuple(list(x)+[val]) for x, val in np.ndenumerate(a)])
|meltlist|_
~~~~~~~~~~~~
@@ -336,7 +335,7 @@ In Python, this list would be a list of tuples, so
.. ipython:: python
a = list(enumerate(list(range(1,5))+[np.NAN]))
- DataFrame(a)
+ pd.DataFrame(a)
For more details and examples see :ref:`the Into to Data Structures
documentation <basics.dataframe.from_items>`.
@@ -361,7 +360,7 @@ In Python, the :meth:`~pandas.melt` method is the R equivalent:
.. ipython:: python
- cheese = DataFrame({'first' : ['John', 'Mary'],
+ cheese = pd.DataFrame({'first' : ['John', 'Mary'],
'last' : ['Doe', 'Bo'],
'height' : [5.5, 6.0],
'weight' : [130, 150]})
@@ -394,7 +393,7 @@ In Python the best way is to make use of :meth:`~pandas.pivot_table`:
.. ipython:: python
- df = DataFrame({
+ df = pd.DataFrame({
'x': np.random.uniform(1., 168., 12),
'y': np.random.uniform(7., 334., 12),
'z': np.random.uniform(1.7, 20.7, 12),
@@ -426,7 +425,7 @@ using :meth:`~pandas.pivot_table`:
.. ipython:: python
- df = DataFrame({
+ df = pd.DataFrame({
'Animal': ['Animal1', 'Animal2', 'Animal3', 'Animal2', 'Animal1',
'Animal2', 'Animal3'],
'FeedType': ['A', 'B', 'A', 'A', 'B', 'B', 'A'],
@@ -444,6 +443,30 @@ The second approach is to use the :meth:`~pandas.DataFrame.groupby` method:
For more details and examples see :ref:`the reshaping documentation
<reshaping.pivot>` or :ref:`the groupby documentation<groupby.split>`.
+|factor|_
+~~~~~~~~
+
+.. versionadded:: 0.15
+
+pandas has a data type for categorical data.
+
+.. code-block:: r
+
+ cut(c(1,2,3,4,5,6), 3)
+ factor(c(1,2,3,2,2,3))
+
+In pandas this is accomplished with ``pd.cut`` and ``astype("category")``:
+
+.. ipython:: python
+
+ pd.cut(pd.Series([1,2,3,4,5,6]), 3)
+ pd.Series([1,2,3,2,2,3]).astype("category")
+
+For more details and examples see :ref:`categorical introduction <categorical>` and the
+:ref:`API documentation <api.categorical>`. There is also a documentation regarding the
+:ref:`differences to R's factor <categorical.rfactor>`.
+
+
.. |c| replace:: ``c``
.. _c: http://stat.ethz.ch/R-manual/R-patched/library/base/html/c.html
@@ -477,3 +500,5 @@ For more details and examples see :ref:`the reshaping documentation
.. |cast| replace:: ``cast``
.. cast: http://www.inside-r.org/packages/cran/reshape2/docs/cast
+.. |factor| replace:: ``factor``
+.. _factor: https://stat.ethz.ch/R-manual/R-devel/library/base/html/factor.html
\ No newline at end of file
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 8c0e193ec6348..55e2c440754b1 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -540,21 +540,18 @@ Categoricals in Series/DataFrame
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:class:`~pandas.Categorical` can now be included in `Series` and `DataFrames` and gained new
-methods to manipulate. Thanks to Jan Schultz for much of this API/implementation. (:issue:`3943`, :issue:`5313`, :issue:`5314`,
+methods to manipulate. Thanks to Jan Schulz for much of this API/implementation. (:issue:`3943`, :issue:`5313`, :issue:`5314`,
:issue:`7444`, :issue:`7839`, :issue:`7848`, :issue:`7864`, :issue:`7914`, :issue:`7768`, :issue:`8006`, :issue:`3678`,
:issue:`8075`, :issue:`8076`, :issue:`8143`).
-For full docs, see the :ref:`Categorical introduction <categorical>` and the
+For full docs, see the :ref:`categorical introduction <categorical>` and the
:ref:`API documentation <api.categorical>`.
.. ipython:: python
df = pd.DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']})
- # convert the raw grades to a categorical
- df["grade"] = pd.Categorical(df["raw_grade"])
-
- # Alternative: df["grade"] = df["raw_grade"].astype("category")
+ df["grade"] = df["raw_grade"].astype("category")
df["grade"]
# Rename the categories
diff --git a/pandas/tools/tile.py b/pandas/tools/tile.py
index 06fee377be749..5eddd2f8dec33 100644
--- a/pandas/tools/tile.py
+++ b/pandas/tools/tile.py
@@ -34,7 +34,8 @@ def cut(x, bins, right=True, labels=None, retbins=False, precision=3,
right == True (the default), then the bins [1,2,3,4] indicate
(1,2], (2,3], (3,4].
labels : array or boolean, default None
- Labels to use for bins, or False to return integer bin labels.
+ Used as labels for the resulting bins. Must be of the same length as the resulting
+ bins. If False, return only integer indicators of the bins.
retbins : bool, optional
Whether to return the bins or not. Can be useful if bins is given
as a scalar.
@@ -47,7 +48,8 @@ def cut(x, bins, right=True, labels=None, retbins=False, precision=3,
-------
out : Categorical or Series or array of integers if labels is False
The return type (Categorical or Series) depends on the input: a Series of type category if
- input is a Series else Categorical.
+ input is a Series else Categorical. Bins are represented as categories when categorical
+ data is returned.
bins : ndarray of floats
Returned only if `retbins` is True.
@@ -63,12 +65,15 @@ def cut(x, bins, right=True, labels=None, retbins=False, precision=3,
Examples
--------
- >>> cut(np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1]), 3, retbins=True)
- (array([(0.191, 3.367], (0.191, 3.367], (0.191, 3.367], (3.367, 6.533],
- (6.533, 9.7], (0.191, 3.367]], dtype=object),
- array([ 0.1905 , 3.36666667, 6.53333333, 9.7 ]))
- >>> cut(np.ones(5), 4, labels=False)
- array([2, 2, 2, 2, 2])
+ >>> pd.cut(np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1]), 3, retbins=True)
+ ([(0.191, 3.367], (0.191, 3.367], (0.191, 3.367], (3.367, 6.533], (6.533, 9.7], (0.191, 3.367]]
+ Categories (3, object): [(0.191, 3.367] < (3.367, 6.533] < (6.533, 9.7]],
+ array([ 0.1905 , 3.36666667, 6.53333333, 9.7 ]))
+ >>> pd.cut(np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1]), 3, labels=["good","medium","bad"])
+ [good, good, good, medium, bad, good]
+ Categories (3, object): [good < medium < bad]
+ >>> pd.cut(np.ones(5), 4, labels=False)
+ array([1, 1, 1, 1, 1], dtype=int64)
"""
# NOTE: this binning code is changed a bit from histogram for var(x) == 0
if not np.iterable(bins):
@@ -126,7 +131,8 @@ def qcut(x, q, labels=None, retbins=False, precision=3):
Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately
array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles
labels : array or boolean, default None
- Labels to use for bin edges, or False to return integer bin labels
+ Used as labels for the resulting bins. Must be of the same length as the resulting
+ bins. If False, return only integer indicators of the bins.
retbins : bool, optional
Whether to return the bins or not. Can be useful if bins is given
as a scalar.
@@ -135,8 +141,12 @@ def qcut(x, q, labels=None, retbins=False, precision=3):
Returns
-------
- cat : Categorical or Series
- Returns a Series of type category if input is a Series else Categorical.
+ out : Categorical or Series or array of integers if labels is False
+ The return type (Categorical or Series) depends on the input: a Series of type category if
+ input is a Series else Categorical. Bins are represented as categories when categorical
+ data is returned.
+ bins : ndarray of floats
+ Returned only if `retbins` is True.
Notes
-----
@@ -144,6 +154,14 @@ def qcut(x, q, labels=None, retbins=False, precision=3):
Examples
--------
+ >>> pd.qcut(range(5), 4)
+ [[0, 1], [0, 1], (1, 2], (2, 3], (3, 4]]
+ Categories (4, object): [[0, 1] < (1, 2] < (2, 3] < (3, 4]]
+ >>> pd.qcut(range(5), 3, labels=["good","medium","bad"])
+ [good, good, medium, bad, bad]
+ Categories (3, object): [good < medium < bad]
+ >>> pd.qcut(range(5), 4, labels=False)
+ array([0, 0, 1, 2, 3], dtype=int64)
"""
if com.is_integer(q):
quantiles = np.linspace(0, 1, q + 1)
| Minor doc updates as part of #8375
- docstring in in cut/qcut + docstring examples #8077 (comment)
- whatsnew: In the note change "levels" to "categories" and s/Schultz/Schulz/
| https://api.github.com/repos/pandas-dev/pandas/pulls/8413 | 2014-09-29T13:04:23Z | 2014-09-29T21:36:42Z | 2014-09-29T21:36:42Z | 2014-09-29T21:36:53Z |
BENCH: programmatically create benchmarks for large ngroups (GH6787) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 8c0e193ec6348..0d003b9f80588 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -813,6 +813,7 @@ Performance
- Performance and memory usage improvements in multi-key ``groupby`` (:issue:`8128`)
- Performance improvements in groupby ``.agg`` and ``.apply`` where builtins max/min were not mapped to numpy/cythonized versions (:issue:`7722`)
- Performance improvement in writing to sql (``to_sql``) of up to 50% (:issue:`8208`).
+- Performance benchmarking of groupby for large value of ngroups (:issue:`6787`)
diff --git a/vb_suite/groupby.py b/vb_suite/groupby.py
index c9746359b6ecd..ec1befa53d383 100644
--- a/vb_suite/groupby.py
+++ b/vb_suite/groupby.py
@@ -484,3 +484,78 @@ def f(g):
groupby_agg_builtins1 = Benchmark("df.groupby('jim').agg([sum, min, max])", setup)
groupby_agg_builtins2 = Benchmark("df.groupby(['jim', 'joe']).agg([sum, min, max])", setup)
+
+#----------------------------------------------------------------------
+# groupby with a variable value for ngroups
+
+
+ngroups_list = [100, 10000]
+no_arg_func_list = [
+ 'all',
+ 'any',
+ 'count',
+ 'cumcount',
+ 'cummax',
+ 'cummin',
+ 'cumprod',
+ 'cumsum',
+ 'describe',
+ 'diff',
+ 'first',
+ 'head',
+ 'last',
+ 'mad',
+ 'max',
+ 'mean',
+ 'median',
+ 'min',
+ 'nunique',
+ 'pct_change',
+ 'prod',
+ 'rank',
+ 'sem',
+ 'size',
+ 'skew',
+ 'std',
+ 'sum',
+ 'tail',
+ 'unique',
+ 'var',
+ 'value_counts',
+]
+
+
+_stmt_template = "df.groupby('value')['timestamp'].%s"
+_setup_template = common_setup + """
+np.random.seed(1234)
+ngroups = %s
+size = ngroups * 10
+rng = np.arange(ngroups)
+df = DataFrame(dict(
+ timestamp=rng.take(np.random.randint(0, ngroups, size=size)),
+ value=np.random.randint(0, size, size=size)
+))
+"""
+START_DATE = datetime(2011, 7, 1)
+
+
+def make_large_ngroups_bmark(ngroups, func_name, func_args=''):
+ bmark_name = 'groupby_ngroups_%s_%s' % (ngroups, func_name)
+ stmt = _stmt_template % ('%s(%s)' % (func_name, func_args))
+ setup = _setup_template % ngroups
+ bmark = Benchmark(stmt, setup, start_date=START_DATE)
+ # MUST set name
+ bmark.name = bmark_name
+ return bmark
+
+
+def inject_bmark_into_globals(bmark):
+ if not bmark.name:
+ raise AssertionError('benchmark must have a name')
+ globals()[bmark.name] = bmark
+
+
+for ngroups in ngroups_list:
+ for func_name in no_arg_func_list:
+ bmark = make_large_ngroups_bmark(ngroups, func_name)
+ inject_bmark_into_globals(bmark)
| closes #6787
Uses ngroups=10000 as suggested in the issue, which takes about 1 hour on my desktop.
For results (vb_suite.log, pkl file) see: https://gist.github.com/dlovell/ea3400273314e7612f6e
Note: gist references a different commit hash. I changed the commit message and added modification to doc/source/v0.15.0.txt, but the actual modifications to vb_suite/groupby.py are principally the same.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8410 | 2014-09-28T17:52:25Z | 2014-09-30T15:53:52Z | 2014-09-30T15:53:52Z | 2014-09-30T15:59:30Z |
Allow importing pandas without setuptools | diff --git a/doc/source/install.rst b/doc/source/install.rst
index 2dfda3be0dcd4..0331e8a47903c 100644
--- a/doc/source/install.rst
+++ b/doc/source/install.rst
@@ -302,6 +302,8 @@ Optional Dependencies
* Google's `python-gflags <http://code.google.com/p/python-gflags/>`__
and `google-api-python-client <http://github.com/google/google-api-python-client>`__
* Needed for :mod:`~pandas.io.gbq`
+* `setuptools <https://pypi.python.org/pypi/setuptools/>`__
+ * Needed for :mod:`~pandas.io.gbq` (specifically, it utilizes `pkg_resources`)
* `httplib2 <http://pypi.python.org/pypi/httplib2>`__
* Needed for :mod:`~pandas.io.gbq`
* One of the following combinations of libraries is needed to use the
diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index 76848a62d0d5f..abb743d3ba04e 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -6,7 +6,6 @@
import uuid
import numpy as np
-import pkg_resources
from distutils.version import LooseVersion
from pandas import compat
@@ -20,46 +19,54 @@
_GOOGLE_FLAGS_INSTALLED = False
_GOOGLE_FLAGS_VALID_VERSION = False
_HTTPLIB2_INSTALLED = False
+_SETUPTOOLS_INSTALLED = False
if not compat.PY3:
-
+
try:
- from apiclient.discovery import build
- from apiclient.http import MediaFileUpload
- from apiclient.errors import HttpError
+ import pkg_resources
+ _SETUPTOOLS_INSTALLED = True
+ except ImportError:
+ _SETUPTOOLS_INSTALLED = False
+
+ if _SETUPTOOLS_INSTALLED:
+ try:
+ from apiclient.discovery import build
+ from apiclient.http import MediaFileUpload
+ from apiclient.errors import HttpError
- from oauth2client.client import OAuth2WebServerFlow
- from oauth2client.client import AccessTokenRefreshError
- from oauth2client.client import flow_from_clientsecrets
- from oauth2client.file import Storage
- from oauth2client.tools import run
- _GOOGLE_API_CLIENT_INSTALLED=True
- _GOOGLE_API_CLIENT_VERSION = pkg_resources.get_distribution('google-api-python-client').version
+ from oauth2client.client import OAuth2WebServerFlow
+ from oauth2client.client import AccessTokenRefreshError
+ from oauth2client.client import flow_from_clientsecrets
+ from oauth2client.file import Storage
+ from oauth2client.tools import run
+ _GOOGLE_API_CLIENT_INSTALLED=True
+ _GOOGLE_API_CLIENT_VERSION = pkg_resources.get_distribution('google-api-python-client').version
- if LooseVersion(_GOOGLE_API_CLIENT_VERSION >= '1.2.0'):
- _GOOGLE_API_CLIENT_VALID_VERSION = True
+ if LooseVersion(_GOOGLE_API_CLIENT_VERSION >= '1.2.0'):
+ _GOOGLE_API_CLIENT_VALID_VERSION = True
- except ImportError:
- _GOOGLE_API_CLIENT_INSTALLED = False
+ except ImportError:
+ _GOOGLE_API_CLIENT_INSTALLED = False
- try:
- import gflags as flags
- _GOOGLE_FLAGS_INSTALLED = True
+ try:
+ import gflags as flags
+ _GOOGLE_FLAGS_INSTALLED = True
- _GOOGLE_FLAGS_VERSION = pkg_resources.get_distribution('python-gflags').version
+ _GOOGLE_FLAGS_VERSION = pkg_resources.get_distribution('python-gflags').version
- if LooseVersion(_GOOGLE_FLAGS_VERSION >= '2.0.0'):
- _GOOGLE_FLAGS_VALID_VERSION = True
+ if LooseVersion(_GOOGLE_FLAGS_VERSION >= '2.0.0'):
+ _GOOGLE_FLAGS_VALID_VERSION = True
- except ImportError:
- _GOOGLE_FLAGS_INSTALLED = False
+ except ImportError:
+ _GOOGLE_FLAGS_INSTALLED = False
- try:
- import httplib2
- _HTTPLIB2_INSTALLED = True
- except ImportError:
- _HTTPLIB2_INSTALLED = False
+ try:
+ import httplib2
+ _HTTPLIB2_INSTALLED = True
+ except ImportError:
+ _HTTPLIB2_INSTALLED = False
logger = logging.getLogger('pandas.io.gbq')
@@ -296,10 +303,14 @@ def _test_imports():
_GOOGLE_FLAGS_INSTALLED
_GOOGLE_FLAGS_VALID_VERSION
_HTTPLIB2_INSTALLED
+ _SETUPTOOLS_INSTALLED
if compat.PY3:
raise NotImplementedError("Google's libraries do not support Python 3 yet")
+ if not _SETUPTOOLS_INSTALLED:
+ raise ImportError('Could not import pkg_resources (setuptools).')
+
if not _GOOGLE_API_CLIENT_INSTALLED:
raise ImportError('Could not import Google API Client.')
| Possible solution for https://github.com/pydata/pandas/pull/8107#issuecomment-57017595
| https://api.github.com/repos/pandas-dev/pandas/pulls/8409 | 2014-09-27T21:11:34Z | 2014-09-29T13:23:48Z | 2014-09-29T13:23:48Z | 2014-09-29T13:24:23Z |
Added a section to FAQ Docs about startup scripts for setting up pandas based on issue #5748. | diff --git a/doc/source/faq.rst b/doc/source/faq.rst
index a613d53218ce2..6aa51346f008a 100644
--- a/doc/source/faq.rst
+++ b/doc/source/faq.rst
@@ -65,6 +65,28 @@ Monkey-patching existing methods is usually a bad idea in that respect.
When used with proper care, however, it's a very useful tool to have.
+.. _ref-python-startup:
+
+Setting startup options for pandas in python/ipython environment
+----------------------------------------------------------------
+
+Using startup scripts for the python/ipython environment to import pandas and set options makes working with pandas more efficient. To do this, create a .py or .ipy script in the startup directory of the desired profile. An example where the startup folder is in a default ipython profile can be found at:
+
+.. code-block:: python
+
+ $IPYTHONDIR/profile_default/startup
+
+More information can be found in the `ipython profile documentation
+<http://ipython.org/ipython-doc/1/config/overview.html>`__. An example startup script for pandas is displayed below:
+
+.. code-block:: python
+
+ import pandas as pd
+ pd.set_option('display.max_rows', 999)
+ pd.set_option('precision', 5)
+
+For a list of options available for pandas, see the :ref:`pandas options documentation <options>`.
+
.. _ref-scikits-migration:
Migrating from scikits.timeseries to pandas >= 0.8.0
diff --git a/doc/source/options.rst b/doc/source/options.rst
index 1e8517014bfc5..420e4f20261ca 100644
--- a/doc/source/options.rst
+++ b/doc/source/options.rst
@@ -86,6 +86,8 @@ pandas namespace. To change an option, call ``set_option('option regex', new_va
pd.set_option('mode.sim_interactive', True)
pd.get_option('mode.sim_interactive')
+**Note:** that the option 'mode.sim_interactive' is mostly used for debugging purposes.
+
All options also have a default value, and you can use ``reset_option`` to do just that:
.. ipython:: python
| Closes #5748
| https://api.github.com/repos/pandas-dev/pandas/pulls/8407 | 2014-09-27T20:09:11Z | 2014-09-27T21:06:30Z | 2014-09-27T21:06:30Z | 2014-11-28T15:41:45Z |
CLN: Remove core/array.py | diff --git a/pandas/core/array.py b/pandas/core/array.py
deleted file mode 100644
index 495f231921a19..0000000000000
--- a/pandas/core/array.py
+++ /dev/null
@@ -1,37 +0,0 @@
-"""
-Isolate pandas's exposure to NumPy
-"""
-
-import numpy as np
-
-Array = np.ndarray
-
-bool = np.bool_
-
-_dtypes = {
- 'int': [8, 16, 32, 64],
- 'uint': [8, 16, 32, 64],
- 'float': [16, 32, 64]
-}
-
-_lift_types = []
-
-for _k, _v in _dtypes.items():
- for _i in _v:
- _lift_types.append(_k + str(_i))
-
-for _t in _lift_types:
- globals()[_t] = getattr(np, _t)
-
-_lift_function = ['empty', 'arange', 'array', 'putmask', 'where']
-
-for _f in _lift_function:
- globals()[_f] = getattr(np, _f)
-
-_lift_random = ['randn', 'rand']
-
-for _f in _lift_random:
- globals()[_f] = getattr(np.random, _f)
-
-NA = np.nan
-
diff --git a/pandas/core/common.py b/pandas/core/common.py
index e138668b369fe..a3698c569b8b3 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -22,7 +22,6 @@
from pandas.compat import StringIO, BytesIO, range, long, u, zip, map
from pandas.core.config import get_option
-from pandas.core import array as pa
class PandasError(Exception):
pass
@@ -999,7 +998,7 @@ def _infer_dtype_from_scalar(val):
dtype = np.object_
# a 1-element ndarray
- if isinstance(val, pa.Array):
+ if isinstance(val, np.ndarray):
if val.ndim != 0:
raise ValueError(
"invalid ndarray passed to _infer_dtype_from_scalar")
@@ -1350,7 +1349,7 @@ def _fill_zeros(result, x, y, name, fill):
if not isinstance(y, np.ndarray):
dtype, value = _infer_dtype_from_scalar(y)
- y = pa.empty(result.shape, dtype=dtype)
+ y = np.empty(result.shape, dtype=dtype)
y.fill(value)
if is_integer_dtype(y):
@@ -1575,7 +1574,7 @@ def _interp_limit(invalid, limit):
inds = np.asarray(xvalues)
# hack for DatetimeIndex, #1646
if issubclass(inds.dtype.type, np.datetime64):
- inds = inds.view(pa.int64)
+ inds = inds.view(np.int64)
if inds.dtype == np.object_:
inds = lib.maybe_convert_objects(inds)
diff --git a/pandas/core/ops.py b/pandas/core/ops.py
index 7e0dae91f465d..2c7d92afe3b79 100644
--- a/pandas/core/ops.py
+++ b/pandas/core/ops.py
@@ -12,7 +12,6 @@
import pandas.index as _index
from pandas.util.decorators import Appender
import pandas.core.common as com
-import pandas.core.array as pa
import pandas.computation.expressions as expressions
from pandas.core.common import(bind_method, is_list_like, notnull, isnull,
_values_from_object, _maybe_match_name)
@@ -332,7 +331,7 @@ def _convert_to_array(self, values, name=None, other=None):
# a datelike
elif isinstance(values, pd.DatetimeIndex):
values = values.to_series()
- elif not (isinstance(values, (pa.Array, pd.Series)) and
+ elif not (isinstance(values, (np.ndarray, pd.Series)) and
com.is_datetime64_dtype(values)):
values = tslib.array_to_datetime(values)
elif inferred_type in ('timedelta', 'timedelta64'):
@@ -349,7 +348,7 @@ def _convert_to_array(self, values, name=None, other=None):
"operation [{0}]".format(name))
elif isinstance(values[0], pd.DateOffset):
# handle DateOffsets
- os = pa.array([getattr(v, 'delta', None) for v in values])
+ os = np.array([getattr(v, 'delta', None) for v in values])
mask = isnull(os)
if mask.any():
raise TypeError("cannot use a non-absolute DateOffset in "
@@ -366,10 +365,10 @@ def _convert_to_array(self, values, name=None, other=None):
else:
raise TypeError(
'incompatible type [{0}] for a datetime/timedelta '
- 'operation'.format(pa.array(values).dtype))
+ 'operation'.format(np.array(values).dtype))
else:
raise TypeError("incompatible type [{0}] for a datetime/timedelta"
- " operation".format(pa.array(values).dtype))
+ " operation".format(np.array(values).dtype))
return values
@@ -408,7 +407,7 @@ def _convert_for_datetime(self, lvalues, rvalues):
if mask is not None:
if mask.any():
def f(x):
- x = pa.array(x, dtype=self.dtype)
+ x = np.array(x, dtype=self.dtype)
np.putmask(x, mask, self.fill_value)
return x
self.wrap_results = f
@@ -449,19 +448,19 @@ def na_op(x, y):
result = expressions.evaluate(op, str_rep, x, y,
raise_on_error=True, **eval_kwargs)
except TypeError:
- if isinstance(y, (pa.Array, pd.Series, pd.Index)):
+ if isinstance(y, (np.ndarray, pd.Series, pd.Index)):
dtype = np.find_common_type([x.dtype, y.dtype], [])
result = np.empty(x.size, dtype=dtype)
mask = notnull(x) & notnull(y)
result[mask] = op(x[mask], _values_from_object(y[mask]))
- elif isinstance(x, pa.Array):
- result = pa.empty(len(x), dtype=x.dtype)
+ elif isinstance(x, np.ndarray):
+ result = np.empty(len(x), dtype=x.dtype)
mask = notnull(x)
result[mask] = op(x[mask], y)
else:
raise TypeError("{typ} cannot perform the operation {op}".format(typ=type(x).__name__,op=str_rep))
- result, changed = com._maybe_upcast_putmask(result, ~mask, pa.NA)
+ result, changed = com._maybe_upcast_putmask(result, ~mask, np.nan)
result = com._fill_zeros(result, x, y, name, fill_zeros)
return result
@@ -531,7 +530,7 @@ def na_op(x, y):
if isinstance(y, list):
y = lib.list_to_object_array(y)
- if isinstance(y, (pa.Array, pd.Series)):
+ if isinstance(y, (np.ndarray, pd.Series)):
if y.dtype != np.object_:
result = lib.vec_compare(x, y.astype(np.object_), op)
else:
@@ -558,7 +557,7 @@ def wrapper(self, other):
index=self.index, name=name)
elif isinstance(other, pd.DataFrame): # pragma: no cover
return NotImplemented
- elif isinstance(other, (pa.Array, pd.Index)):
+ elif isinstance(other, (np.ndarray, pd.Index)):
if len(self) != len(other):
raise ValueError('Lengths must match to compare')
return self._constructor(na_op(self.values, np.asarray(other)),
@@ -610,7 +609,7 @@ def na_op(x, y):
if isinstance(y, list):
y = lib.list_to_object_array(y)
- if isinstance(y, (pa.Array, pd.Series)):
+ if isinstance(y, (np.ndarray, pd.Series)):
if (x.dtype == np.bool_ and
y.dtype == np.bool_): # pragma: no cover
result = op(x, y) # when would this be hit?
@@ -688,7 +687,7 @@ def flex_wrapper(self, other, level=None, fill_value=None, axis=0):
self._get_axis_number(axis)
if isinstance(other, pd.Series):
return self._binop(other, op, level=level, fill_value=fill_value)
- elif isinstance(other, (pa.Array, pd.Series, list, tuple)):
+ elif isinstance(other, (np.ndarray, pd.Series, list, tuple)):
if len(other) != len(self):
raise ValueError('Lengths must be equal')
return self._binop(self._constructor(other, self.index), op,
@@ -925,10 +924,10 @@ def na_op(x, y):
except TypeError:
# TODO: might need to find_common_type here?
- result = pa.empty(len(x), dtype=x.dtype)
+ result = np.empty(len(x), dtype=x.dtype)
mask = notnull(x)
result[mask] = op(x[mask], y)
- result, changed = com._maybe_upcast_putmask(result, ~mask, pa.NA)
+ result, changed = com._maybe_upcast_putmask(result, ~mask, np.nan)
result = com._fill_zeros(result, x, y, name, fill_zeros)
return result
diff --git a/pandas/core/series.py b/pandas/core/series.py
index f77d3a60adee2..37f66fc56ea56 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -35,7 +35,6 @@
from pandas.util.terminal import get_terminal_size
from pandas.compat import zip, u, OrderedDict
-import pandas.core.array as pa
import pandas.core.ops as ops
from pandas.core.algorithms import select_n
@@ -145,7 +144,7 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
data = data._to_embed(keep_tz=True)
copy = True
- elif isinstance(data, pa.Array):
+ elif isinstance(data, np.ndarray):
pass
elif isinstance(data, Series):
if name is None:
@@ -165,12 +164,12 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
if isinstance(index, DatetimeIndex):
# coerce back to datetime objects for lookup
data = lib.fast_multiget(data, index.astype('O'),
- default=pa.NA)
+ default=np.nan)
elif isinstance(index, PeriodIndex):
data = [data.get(i, nan) for i in index]
else:
data = lib.fast_multiget(data, index.values,
- default=pa.NA)
+ default=np.nan)
except TypeError:
data = [data.get(i, nan) for i in index]
@@ -558,7 +557,7 @@ def _get_with(self, key):
raise
# pragma: no cover
- if not isinstance(key, (list, pa.Array, Series, Index)):
+ if not isinstance(key, (list, np.ndarray, Series, Index)):
key = list(key)
if isinstance(key, Index):
@@ -688,7 +687,7 @@ def _set_with(self, key, value):
except Exception:
pass
- if not isinstance(key, (list, Series, pa.Array, Series)):
+ if not isinstance(key, (list, Series, np.ndarray, Series)):
try:
key = list(key)
except:
@@ -839,7 +838,7 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False):
resetted : DataFrame, or Series if drop == True
"""
if drop:
- new_index = pa.arange(len(self))
+ new_index = np.arange(len(self))
if level is not None and isinstance(self.index, MultiIndex):
if not isinstance(level, (tuple, list)):
level = [level]
@@ -1111,7 +1110,7 @@ def count(self, level=None):
# call cython function
max_bin = len(level_index)
labels = com._ensure_int64(self.index.labels[level])
- counts = lib.count_level_1d(mask.view(pa.uint8),
+ counts = lib.count_level_1d(mask.view(np.uint8),
labels, max_bin)
return self._constructor(counts,
index=level_index).__finalize__(self)
@@ -1171,7 +1170,7 @@ def idxmin(self, axis=None, out=None, skipna=True):
"""
i = nanops.nanargmin(_values_from_object(self), skipna=skipna)
if i == -1:
- return pa.NA
+ return np.nan
return self.index[i]
def idxmax(self, axis=None, out=None, skipna=True):
@@ -1198,14 +1197,14 @@ def idxmax(self, axis=None, out=None, skipna=True):
"""
i = nanops.nanargmax(_values_from_object(self), skipna=skipna)
if i == -1:
- return pa.NA
+ return np.nan
return self.index[i]
# ndarray compat
argmin = idxmin
argmax = idxmax
- @Appender(pa.Array.round.__doc__)
+ @Appender(np.ndarray.round.__doc__)
def round(self, decimals=0, out=None):
"""
@@ -1280,7 +1279,7 @@ def corr(self, other, method='pearson',
"""
this, other = self.align(other, join='inner', copy=False)
if len(this) == 0:
- return pa.NA
+ return np.nan
return nanops.nancorr(this.values, other.values, method=method,
min_periods=min_periods)
@@ -1302,7 +1301,7 @@ def cov(self, other, min_periods=None):
"""
this, other = self.align(other, join='inner', copy=False)
if len(this) == 0:
- return pa.NA
+ return np.nan
return nanops.nancov(this.values, other.values,
min_periods=min_periods)
@@ -1466,7 +1465,7 @@ def combine(self, other, func, fill_value=nan):
if isinstance(other, Series):
new_index = self.index.union(other.index)
new_name = _maybe_match_name(self, other)
- new_values = pa.empty(len(new_index), dtype=self.dtype)
+ new_values = np.empty(len(new_index), dtype=self.dtype)
for i, idx in enumerate(new_index):
lv = self.get(idx, fill_value)
rv = other.get(idx, fill_value)
@@ -1692,12 +1691,12 @@ def _try_kind_sort(arr):
return arr.argsort(kind='quicksort')
arr = self.values
- sortedIdx = pa.empty(len(self), dtype=np.int32)
+ sortedIdx = np.empty(len(self), dtype=np.int32)
bad = isnull(arr)
good = ~bad
- idx = pa.arange(len(self))
+ idx = np.arange(len(self))
argsorted = _try_kind_sort(arr[good])
@@ -1930,7 +1929,7 @@ def map(self, arg, na_action=None):
mask = isnull(values)
def map_f(values, f):
- return lib.map_infer_mask(values, f, mask.view(pa.uint8))
+ return lib.map_infer_mask(values, f, mask.view(np.uint8))
else:
map_f = lib.map_infer
@@ -2361,7 +2360,7 @@ def asof(self, where):
start = start.ordinal
if where < start:
- return pa.NA
+ return np.nan
loc = self.index.searchsorted(where, side='right')
if loc > 0:
loc -= 1
@@ -2508,18 +2507,18 @@ def _try_cast(arr, take_fast_path):
try:
arr = _possibly_cast_to_datetime(arr, dtype)
- subarr = pa.array(arr, dtype=dtype, copy=copy)
+ subarr = np.array(arr, dtype=dtype, copy=copy)
except (ValueError, TypeError):
if com.is_categorical_dtype(dtype):
subarr = Categorical(arr)
elif dtype is not None and raise_cast_failure:
raise
else:
- subarr = pa.array(arr, dtype=object, copy=copy)
+ subarr = np.array(arr, dtype=object, copy=copy)
return subarr
# GH #846
- if isinstance(data, (pa.Array, Index, Series)):
+ if isinstance(data, (np.ndarray, Index, Series)):
subarr = np.array(data, copy=False)
if dtype is not None:
@@ -2564,7 +2563,7 @@ def _try_cast(arr, take_fast_path):
except Exception:
if raise_cast_failure: # pragma: no cover
raise
- subarr = pa.array(data, dtype=object, copy=copy)
+ subarr = np.array(data, dtype=object, copy=copy)
subarr = lib.maybe_convert_objects(subarr)
else:
@@ -2578,7 +2577,7 @@ def _try_cast(arr, take_fast_path):
# scalar like
if subarr.ndim == 0:
if isinstance(data, list): # pragma: no cover
- subarr = pa.array(data, dtype=object)
+ subarr = np.array(data, dtype=object)
elif index is not None:
value = data
@@ -2589,7 +2588,7 @@ def _try_cast(arr, take_fast_path):
# need to possibly convert the value here
value = _possibly_cast_to_datetime(value, dtype)
- subarr = pa.empty(len(index), dtype=dtype)
+ subarr = np.empty(len(index), dtype=dtype)
subarr.fill(value)
else:
@@ -2602,11 +2601,11 @@ def _try_cast(arr, take_fast_path):
# a 1-element ndarray
if len(subarr) != len(index) and len(subarr) == 1:
value = subarr[0]
- subarr = pa.empty(len(index), dtype=subarr.dtype)
+ subarr = np.empty(len(index), dtype=subarr.dtype)
subarr.fill(value)
elif subarr.ndim > 1:
- if isinstance(data, pa.Array):
+ if isinstance(data, np.ndarray):
raise Exception('Data must be 1-dimensional')
else:
subarr = _asarray_tuplesafe(data, dtype=dtype)
@@ -2614,7 +2613,7 @@ def _try_cast(arr, take_fast_path):
# This is to prevent mixed-type Series getting all casted to
# NumPy string type, e.g. NaN --> '-1#IND'.
if issubclass(subarr.dtype.type, compat.string_types):
- subarr = pa.array(data, dtype=object, copy=copy)
+ subarr = np.array(data, dtype=object, copy=copy)
return subarr
| Fixes https://github.com/pydata/pandas/issues/8359
| https://api.github.com/repos/pandas-dev/pandas/pulls/8406 | 2014-09-27T19:37:12Z | 2014-09-29T13:21:50Z | 2014-09-29T13:21:49Z | 2014-09-29T18:08:00Z |
Better message in exception when conversion from period to timestamp fai... | diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index 7cba1cf6ccffe..e88d88c86cf48 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -1072,8 +1072,7 @@ cdef convert_to_tsobject(object ts, object tz, object unit):
ts = datetime.combine(ts, datetime_time())
return convert_to_tsobject(ts, tz, None)
else:
- raise ValueError("Could not construct Timestamp from argument %s" %
- type(ts))
+ raise ValueError("Cannot convert Period to Timestamp unambiguously. Use to_timestamp")
if obj.value != NPY_NAT:
_check_dts_bounds(&obj.dts)
| Fix to issue https://github.com/pydata/pandas/issues/6780
| https://api.github.com/repos/pandas-dev/pandas/pulls/8405 | 2014-09-27T18:03:29Z | 2014-09-29T14:52:54Z | 2014-09-29T14:52:54Z | 2014-09-29T22:07:51Z |
ENH: First attempt at adding coveralls | diff --git a/.travis.yml b/.travis.yml
index d13509805e0f8..c984082fee34c 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -109,3 +109,4 @@ after_script:
- ci/print_versions.py
- ci/print_skipped.py /tmp/nosetests.xml
- ci/after_script.sh
+ - coveralls
diff --git a/ci/install.sh b/ci/install.sh
index f146f3ba7ee82..408f13007c6b4 100755
--- a/ci/install.sh
+++ b/ci/install.sh
@@ -45,6 +45,7 @@ pip install -I -U setuptools
pip install wheel==0.22
#pip install nose==1.3.3
pip install nose==1.3.4
+pip install coveralls
# comment this line to disable the fetching of wheel files
base_url=http://pandas.pydata.org/pandas-build/dev/wheels
diff --git a/ci/script.sh b/ci/script.sh
index 152a2f1ebdcf9..b7e4fa9236335 100755
--- a/ci/script.sh
+++ b/ci/script.sh
@@ -17,7 +17,7 @@ fi
# doc build log will be shown after tests
echo nosetests --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml
-nosetests --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml
+nosetests --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml --with-coverage --cover-package=pandas
RET="$?"
| First attempt at adding coveralls to pandas
| https://api.github.com/repos/pandas-dev/pandas/pulls/8404 | 2014-09-27T17:05:54Z | 2014-10-04T16:49:11Z | null | 2014-10-04T16:49:11Z |
BUG: Panel.fillna with method='ffill' ignores the axis parameter (GH8251) | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 9f9b543f0fa7d..fad15dc5b53a0 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2220,7 +2220,7 @@ def convert_objects(self, convert_dates=True, convert_numeric=False,
#----------------------------------------------------------------------
# Filling NA's
- def fillna(self, value=None, method=None, axis=0, inplace=False,
+ def fillna(self, value=None, method=None, axis=None, inplace=False,
limit=None, downcast=None):
"""
Fill NA/NaN values using the specified method
@@ -2236,9 +2236,11 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
values specifying which value to use for each index (for a Series) or
column (for a DataFrame). (values not in the dict/Series/DataFrame will not be
filled). This value cannot be a list.
- axis : {0, 1}, default 0
+ axis : {0, 1, 2}
+ Fill along this axis. For a DataFrame:
* 0: fill column-by-column
* 1: fill row-by-row
+ Default: fill column-by-column (0 for DataFrame, 1 for Panel)
inplace : boolean, default False
If True, fill in place. Note: this will modify any
other views on this object, (e.g. a no-copy slice for a column in a
@@ -2263,6 +2265,9 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
'you passed a "{0}"'.format(type(value).__name__))
self._consolidate_inplace()
+ if axis is None:
+ axis = max(0, self.ndim - 2)
+
axis = self._get_axis_number(axis)
method = com._clean_fill_method(method)
@@ -2270,38 +2275,66 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
if value is None:
if method is None:
raise ValueError('must specify a fill method or value')
- if self._is_mixed_type and axis == 1:
+
+ # 2d or less
+ if self.ndim <= 2:
+ if self._is_mixed_type and axis == 1:
+ if inplace:
+ raise NotImplementedError(
+ 'Cannot fill mixed type on axis 1 in place')
+ if downcast:
+ raise NotImplementedError(
+ 'Cannot fill mixed type on axis 1 with downcast')
+
+ result = self.T.fillna(method=method, limit=limit).T
+
+ # need to downcast here because of all of the transposes
+ result._data = result._data.downcast()
+
+ return result
+
+ method = com._clean_fill_method(method)
+ new_data = self._data.interpolate(method=method,
+ axis=axis,
+ limit=limit,
+ inplace=inplace,
+ coerce=True,
+ downcast=downcast)
+
+ # 3d
+ elif self.ndim == 3:
if inplace:
- raise NotImplementedError()
- result = self.T.fillna(method=method, limit=limit).T
+ raise NotImplementedError('Cannot fill Panel in place')
- # need to downcast here because of all of the transposes
- result._data = result._data.downcast()
+ if axis == 0:
+ if downcast:
+ raise NotImplementedError(
+ 'Cannot fill Panel on axis 0 with downcast')
- return result
+ swapped = self.swapaxes(0, 1, copy=False)
+ filled = swapped.fillna(method=method, axis=1, limit=limit)
+ result = filled.swapaxes(0, 1, copy=False)
+
+ # need to downcast here because of all of the transposes
+ result._data = result._data.downcast()
+
+ return result
+
+ else:
+ # fill in 2d chunks
+ result = dict([(col, s.fillna(method=method,
+ axis=axis - 1,
+ limit=limit,
+ downcast=downcast))
+ for col, s in compat.iteritems(self)])
+ return self._constructor.from_dict(result).__finalize__(self)
# > 3d
- if self.ndim > 3:
+ elif self.ndim > 3:
raise NotImplementedError(
'Cannot fillna with a method for > 3dims'
)
- # 3d
- elif self.ndim == 3:
-
- # fill in 2d chunks
- result = dict([(col, s.fillna(method=method, value=value))
- for col, s in compat.iteritems(self)])
- return self._constructor.from_dict(result).__finalize__(self)
-
- # 2d or less
- method = com._clean_fill_method(method)
- new_data = self._data.interpolate(method=method,
- axis=axis,
- limit=limit,
- inplace=inplace,
- coerce=True,
- downcast=downcast)
else:
if method is not None:
raise ValueError('cannot specify both a fill method and value')
@@ -2324,11 +2357,19 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
downcast=downcast)
elif isinstance(value, (dict, com.ABCSeries)):
+ if self.ndim >= 3:
+ raise NotImplementedError('Cannot fillna with a dict/Series '
+ 'for >= 3 dims')
+
if axis == 1:
raise NotImplementedError('Currently only can fill '
'with dict/Series column '
'by column')
+ if downcast:
+ raise NotImplementedError(
+ 'Cannot downcast with dict/Series')
+
result = self if inplace else self.copy()
for k, v in compat.iteritems(value):
if k not in result:
@@ -2336,11 +2377,13 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
obj = result[k]
obj.fillna(v, limit=limit, inplace=True)
return result
+
elif not com.is_list_like(value):
new_data = self._data.fillna(value=value,
limit=limit,
inplace=inplace,
downcast=downcast)
+
elif isinstance(value, DataFrame) and self.ndim == 2:
new_data = self.where(self.notnull(), value)
else:
@@ -2351,12 +2394,12 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
else:
return self._constructor(new_data).__finalize__(self)
- def ffill(self, axis=0, inplace=False, limit=None, downcast=None):
+ def ffill(self, axis=None, inplace=False, limit=None, downcast=None):
"Synonym for NDFrame.fillna(method='ffill')"
return self.fillna(method='ffill', axis=axis, inplace=inplace,
limit=limit, downcast=downcast)
- def bfill(self, axis=0, inplace=False, limit=None, downcast=None):
+ def bfill(self, axis=None, inplace=False, limit=None, downcast=None):
"Synonym for NDFrame.fillna(method='bfill')"
return self.fillna(method='bfill', axis=axis, inplace=inplace,
limit=limit, downcast=downcast)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 80d81f4e283f3..ca7b997aaced3 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -7628,9 +7628,11 @@ def test_fillna_dict_series(self):
expected = df.fillna(df.max().to_dict())
assert_frame_equal(result, expected)
- # disable this for now
+ # disable these for now
with assertRaisesRegexp(NotImplementedError, 'column by column'):
df.fillna(df.max(1), axis=1)
+ with assertRaisesRegexp(NotImplementedError, 'downcast'):
+ df.fillna(df.max(1), downcast='infer')
def test_fillna_dataframe(self):
# GH 8377
@@ -7668,6 +7670,11 @@ def test_fillna_columns(self):
expected = df.astype(float).fillna(method='ffill', axis=1)
assert_frame_equal(result, expected)
+ # disable these for now
+ with assertRaisesRegexp(NotImplementedError, 'axis 1.*in place'):
+ df.fillna(method='ffill', axis=1, inplace=True)
+ with assertRaisesRegexp(NotImplementedError, 'axis 1.*downcast'):
+ df.fillna(method='ffill', axis=1, downcast='infer')
def test_fillna_invalid_method(self):
with assertRaisesRegexp(ValueError, 'ffil'):
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 736cdf312b361..4a3e02aa75867 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -1336,9 +1336,12 @@ def test_sort_index(self):
assert_panel_equal(sorted_panel, self.panel)
def test_fillna(self):
+ # Fill with a value.
filled = self.panel.fillna(0)
self.assertTrue(np.isfinite(filled.values).all())
+ # If no axis is specified, fill along axis 1, equivalent to axis 0 of
+ # each DataFrame.
filled = self.panel.fillna(method='backfill')
assert_frame_equal(filled['ItemA'],
self.panel['ItemA'].fillna(method='backfill'))
@@ -1350,10 +1353,72 @@ def test_fillna(self):
assert_frame_equal(filled['ItemA'],
panel['ItemA'].fillna(method='backfill'))
+ # Fill forward.
+ filled = self.panel.fillna(method='ffill')
+ assert_frame_equal(filled['ItemA'],
+ self.panel['ItemA'].fillna(method='ffill'))
+
+ # With limit.
+ filled = self.panel.fillna(method='backfill', limit=1)
+ assert_frame_equal(filled['ItemA'],
+ self.panel['ItemA'].fillna(method='backfill', limit=1))
+
+ # With downcast.
+ rounded = self.panel.apply(lambda x: x.apply(np.round))
+ filled = rounded.fillna(method='backfill', downcast='infer')
+ assert_frame_equal(filled['ItemA'],
+ rounded['ItemA'].fillna(method='backfill', downcast='infer'))
+
+ # Now explicitly request axis 1.
+ filled = self.panel.fillna(method='backfill', axis=1)
+ assert_frame_equal(filled['ItemA'],
+ self.panel['ItemA'].fillna(method='backfill', axis=0))
+
+ # Fill along axis 2, equivalent to filling along axis 1 of each
+ # DataFrame.
+ filled = self.panel.fillna(method='backfill', axis=2)
+ assert_frame_equal(filled['ItemA'],
+ self.panel['ItemA'].fillna(method='backfill', axis=1))
+
+ # Fill an empty panel.
empty = self.panel.reindex(items=[])
filled = empty.fillna(0)
assert_panel_equal(filled, empty)
+ def test_fillna_axis_0(self):
+ # Forward fill along axis 0, interpolating values across DataFrames.
+ filled = self.panel.fillna(method='ffill', axis=0)
+ nan_indexes = self.panel['ItemB']['C'].index[
+ self.panel['ItemB']['C'].apply(np.isnan)]
+ # Values from ItemA are filled into ItemB.
+ assert_series_equal(filled['ItemB']['C'][nan_indexes],
+ self.panel['ItemA']['C'][nan_indexes])
+
+ # Backfill along axis 0.
+ filled = self.panel.fillna(method='backfill', axis=0)
+ # The test data lacks values that can be backfilled on axis 0.
+ assert_panel_equal(filled, self.panel)
+ # Reverse the panel and backfill along axis 0, to properly test
+ # backfill.
+ reverse_panel = self.panel.reindex_axis(reversed(self.panel.axes[0]))
+ filled = reverse_panel.fillna(method='bfill', axis=0)
+ nan_indexes = reverse_panel['ItemB']['C'].index[
+ reverse_panel['ItemB']['C'].apply(np.isnan)]
+ assert_series_equal(filled['ItemB']['C'][nan_indexes],
+ reverse_panel['ItemA']['C'][nan_indexes])
+
+ # Fill along axis 0 with limit.
+ filled = self.panel.fillna(method='ffill', axis=0, limit=1)
+ a_nan = self.panel['ItemA']['C'].index[
+ self.panel['ItemA']['C'].apply(np.isnan)]
+ b_nan = self.panel['ItemB']['C'].index[
+ self.panel['ItemB']['C'].apply(np.isnan)]
+ # Cells that are nan in ItemB but not in ItemA remain unfilled in
+ # ItemC.
+ self.assertTrue(
+ filled['ItemC']['C'][b_nan.diff(a_nan)].apply(np.isnan).all())
+
+ def test_fillna_error(self):
self.assertRaises(ValueError, self.panel.fillna)
self.assertRaises(ValueError, self.panel.fillna, 5, method='ffill')
@@ -1365,6 +1430,18 @@ def test_fillna(self):
p.iloc[0:2,0:2,0:2] = np.nan
self.assertRaises(NotImplementedError, lambda : p.fillna(999,limit=1))
+ # Method fill is not implemented with inplace=True.
+ self.assertRaises(NotImplementedError,
+ lambda: self.panel.fillna(method='bfill', inplace=True))
+
+ # Method fill is not implemented with downcast on axis=0.
+ self.assertRaises(NotImplementedError,
+ lambda: self.panel.fillna(method='bfill', axis=0, downcast='infer'))
+
+ # Value fill is not implemented with dict.
+ self.assertRaises(NotImplementedError,
+ lambda: self.panel.fillna(value={'a': 'b'}))
+
def test_ffill_bfill(self):
assert_panel_equal(self.panel.ffill(),
self.panel.fillna(method='ffill'))
| Adds support for method-based fillna along the specified axis of a Panel. Also adds some additional validation when calling fillna on DataFrame.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8401 | 2014-09-27T02:41:25Z | 2014-09-27T02:46:24Z | null | 2014-09-28T03:56:16Z |
add support for numpy 1.8+ data types for conversion to r dataframe | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index f0c1d1d8939f1..cd62f222885c2 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -287,7 +287,7 @@ API changes
- ``DataFrame.info()`` now ends its output with a newline character (:issue:`8114`)
- add ``copy=True`` argument to ``pd.concat`` to enable pass thrue of complete blocks (:issue:`8252`)
-
+- Added support for numpy 1.8+ data types (bool_, int_, float_, string_) for conversion to R dataframe (:issue:`8400`)
.. _whatsnew_0150.dt:
diff --git a/pandas/rpy/common.py b/pandas/rpy/common.py
index 5747285deb988..55adad3610816 100644
--- a/pandas/rpy/common.py
+++ b/pandas/rpy/common.py
@@ -4,6 +4,7 @@
"""
from __future__ import print_function
+from distutils.version import LooseVersion
from pandas.compat import zip, range
import numpy as np
@@ -72,7 +73,7 @@ def _list(item):
return list(item)
except TypeError:
return []
-
+
# For iris3, HairEyeColor, UCBAdmissions, Titanic
dim = list(obj.dim)
values = np.array(list(obj))
@@ -101,9 +102,9 @@ def _convert_vector(obj):
except AttributeError:
return list(obj)
if 'names' in attributes:
- return pd.Series(list(obj), index=r['names'](obj))
+ return pd.Series(list(obj), index=r['names'](obj))
elif 'tsp' in attributes:
- return pd.Series(list(obj), index=r['time'](obj))
+ return pd.Series(list(obj), index=r['time'](obj))
elif 'labels' in attributes:
return pd.Series(list(obj), index=r['labels'](obj))
if _rclass(obj) == 'dist':
@@ -268,6 +269,7 @@ def convert_to_r_posixct(obj):
np.str: robj.StrVector,
np.bool: robj.BoolVector}
+
NA_TYPES = {np.float64: robj.NA_Real,
np.float32: robj.NA_Real,
np.float: robj.NA_Real,
@@ -279,6 +281,16 @@ def convert_to_r_posixct(obj):
np.bool: robj.NA_Logical}
+if LooseVersion(np.__version__) >= LooseVersion('1.8'):
+ for dict_ in (VECTOR_TYPES, NA_TYPES):
+ dict_.update({
+ np.bool_: dict_[np.bool],
+ np.int_: dict_[np.int],
+ np.float_: dict_[np.float],
+ np.string_: dict_[np.str]
+ })
+
+
def convert_to_r_dataframe(df, strings_as_factors=False):
"""
Convert a pandas DataFrame to a R data.frame.
| Numpy changed the names of their data types in 1.8
http://docs.scipy.org/doc/numpy-dev/user/basics.types.html
specifically, bool, int, float, and complex are now bool_, int_, float_ and complex_
this requires changing the VECTOR_TYPES and NA_TYPES dictionaries used by convert_to_r_dataframe in pandas/rpy/common.py
numpy 1.7 isn't feasible to include as a project dependency (too many packages require 1.8)
Unfortunately, bool_ etc don't exist in numpy < 1.8, so you'll have to try/except that bit. I can change it and submit a pull request if you like
| https://api.github.com/repos/pandas-dev/pandas/pulls/8400 | 2014-09-26T23:47:03Z | 2014-09-29T21:42:44Z | 2014-09-29T21:42:44Z | 2014-09-29T21:42:52Z |
BUG: inconsisten panel indexing with aligning frame (GH7763) | diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index a99d056419ad2..27a31a13a0259 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -609,7 +609,13 @@ def _align_series(self, indexer, ser):
def _align_frame(self, indexer, df):
is_frame = self.obj.ndim == 2
is_panel = self.obj.ndim >= 3
+
if isinstance(indexer, tuple):
+
+ aligners = [not _is_null_slice(idx) for idx in indexer]
+ sum_aligners = sum(aligners)
+ single_aligner = sum_aligners == 1
+
idx, cols = None, None
sindexers = []
for i, ix in enumerate(indexer):
@@ -626,13 +632,21 @@ def _align_frame(self, indexer, df):
# panel
if is_panel:
- if len(sindexers) == 1 and idx is None and cols is None:
- if sindexers[0] == 0:
- df = df.T
- return self.obj.conform(df, axis=sindexers[0])
- df = df.T
+
+ # need to conform to the convention
+ # as we are not selecting on the items axis
+ # and we have a single indexer
+ # GH 7763
+ if len(sindexers) == 1 and sindexers[0] != 0:
+ df = df.T
+
+ if idx is None:
+ idx = df.index
+ if cols is None:
+ cols = df.columns
if idx is not None and cols is not None:
+
if df.index.equals(idx) and df.columns.equals(cols):
val = df.copy().values
else:
@@ -655,21 +669,15 @@ def _align_frame(self, indexer, df):
val = df.reindex(index=ax).values
return val
- elif np.isscalar(indexer) and not is_frame:
+ elif np.isscalar(indexer) and is_panel:
idx = self.obj.axes[1]
cols = self.obj.axes[2]
# by definition we are indexing on the 0th axis
- if is_panel:
- df = df.T
-
- if idx.equals(df.index) and cols.equals(df.columns):
- return df.copy().values
-
# a passed in dataframe which is actually a transpose
# of what is needed
- elif idx.equals(df.columns) and cols.equals(df.index):
- return df.T.copy().values
+ if idx.equals(df.index) and cols.equals(df.columns):
+ return df.copy().values
return df.reindex(idx, columns=cols).values
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 27a6b844bccb5..7831fe811c2ff 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -2291,6 +2291,33 @@ def test_panel_getitem(self):
test1 = panel.ix[:, "2002"]
tm.assert_panel_equal(test1,test2)
+ def test_panel_setitem(self):
+
+ # GH 7763
+ # loc and setitem have setting differences
+ np.random.seed(0)
+ index=range(3)
+ columns = list('abc')
+
+ panel = Panel({'A' : DataFrame(np.random.randn(3, 3), index=index, columns=columns),
+ 'B' : DataFrame(np.random.randn(3, 3), index=index, columns=columns),
+ 'C' : DataFrame(np.random.randn(3, 3), index=index, columns=columns)
+ })
+
+ replace = DataFrame(np.eye(3,3), index=range(3), columns=columns)
+ expected = Panel({ 'A' : replace, 'B' : replace, 'C' : replace })
+
+ p = panel.copy()
+ for idx in list('ABC'):
+ p[idx] = replace
+ tm.assert_panel_equal(p, expected)
+
+ p = panel.copy()
+ for idx in list('ABC'):
+ p.loc[idx,:,:] = replace
+ tm.assert_panel_equal(p, expected)
+
+
def test_panel_assignment(self):
# GH3777
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 8234e5a1065e5..736cdf312b361 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -668,24 +668,42 @@ def test_ix_align(self):
def test_ix_frame_align(self):
from pandas import DataFrame
- df = DataFrame(np.random.randn(2, 10))
- df.sort_index(inplace=True)
- p_orig = Panel(np.random.randn(3, 10, 2))
+ p_orig = tm.makePanel()
+ df = p_orig.ix[0].copy()
+ assert_frame_equal(p_orig['ItemA'],df)
p = p_orig.copy()
p.ix[0, :, :] = df
- out = p.ix[0, :, :].T.reindex(df.index, columns=df.columns)
- assert_frame_equal(out, df)
+ assert_panel_equal(p, p_orig)
p = p_orig.copy()
p.ix[0] = df
- out = p.ix[0].T.reindex(df.index, columns=df.columns)
- assert_frame_equal(out, df)
+ assert_panel_equal(p, p_orig)
+
+ p = p_orig.copy()
+ p.iloc[0, :, :] = df
+ assert_panel_equal(p, p_orig)
+
+ p = p_orig.copy()
+ p.iloc[0] = df
+ assert_panel_equal(p, p_orig)
+
+ p = p_orig.copy()
+ p.loc['ItemA'] = df
+ assert_panel_equal(p, p_orig)
+
+ p = p_orig.copy()
+ p.loc['ItemA', :, :] = df
+ assert_panel_equal(p, p_orig)
+
+ p = p_orig.copy()
+ p['ItemA'] = df
+ assert_panel_equal(p, p_orig)
p = p_orig.copy()
p.ix[0, [0, 1, 3, 5], -2:] = df
out = p.ix[0, [0, 1, 3, 5], -2:]
- assert_frame_equal(out, df.T.reindex([0, 1, 3, 5], p.minor_axis[-2:]))
+ assert_frame_equal(out, df.iloc[[0,1,3,5],[2,3]])
# GH3830, panel assignent by values/frame
for dtype in ['float64','int64']:
| closes #7763
| https://api.github.com/repos/pandas-dev/pandas/pulls/8399 | 2014-09-26T23:36:27Z | 2014-09-26T23:36:40Z | 2014-09-26T23:36:40Z | 2014-09-26T23:36:40Z |
TST: Skip failing boxplot tests on mpl 1.4+ | diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index fac6a4d83e13b..1cc5e2a99148b 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -28,6 +28,15 @@
import pandas.tools.plotting as plotting
+def _skip_if_mpl_14_or_dev_boxplot():
+ # GH 8382
+ # Boxplot failures on 1.4 and 1.4.1
+ # Don't need try / except since that's done at class level
+ import matplotlib
+ if matplotlib.__version__ in ('1.4.0', '1.5.x'):
+ raise nose.SkipTest("Matplotlib Regression in 1.4 and current dev.")
+
+
def _skip_if_no_scipy_gaussian_kde():
try:
import scipy
@@ -1790,6 +1799,7 @@ def test_bar_log_subplots(self):
@slow
def test_boxplot(self):
+ _skip_if_mpl_14_or_dev_boxplot()
df = self.hist_df
series = df['height']
numeric_cols = df._get_numeric_data().columns
@@ -1823,6 +1833,7 @@ def test_boxplot(self):
@slow
def test_boxplot_vertical(self):
+ _skip_if_mpl_14_or_dev_boxplot()
df = self.hist_df
series = df['height']
numeric_cols = df._get_numeric_data().columns
@@ -1982,6 +1993,7 @@ def _check_ax_limits(col, ax):
@slow
def test_boxplot_empty_column(self):
+ _skip_if_mpl_14_or_dev_boxplot()
df = DataFrame(np.random.randn(20, 4))
df.loc[:, 0] = np.nan
_check_plot_works(df.boxplot, return_type='axes')
| Closes https://github.com/pydata/pandas/issues/8382
| https://api.github.com/repos/pandas-dev/pandas/pulls/8398 | 2014-09-26T15:00:41Z | 2014-09-27T13:08:26Z | 2014-09-27T13:08:26Z | 2017-04-05T02:05:56Z |
BUG: maintain order in excluding categories | diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index 9ee0018500b00..c4ec556abb2cf 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -641,12 +641,17 @@ def remove_categories(self, removals, inplace=False):
remove_unused_categories
set_categories
"""
- if not com.is_list_like(removals):
- removals = [removals]
- not_included = set(removals) - set(self._categories)
+ removals = set(removals if com.is_list_like(removals) else [removals])
+ not_included = removals - set(self._categories)
+
if len(not_included) != 0:
raise ValueError("removals must all be in old categories: %s" % str(not_included))
- new_categories = set(self._categories) - set(removals)
+
+ # order matters, set collections/operations are unordered
+ # new_categories != set(self._categories) - removals
+ pred = lambda cat: cat not in removals # filtering predicate for cats
+ new_categories = list(filter(pred, self._categories))
+
return self.set_categories(new_categories, ordered=self.ordered, rename=False,
inplace=inplace)
@@ -1414,4 +1419,3 @@ def _convert_to_list_like(list_like):
else:
# is this reached?
return [list_like]
-
| should fix current travis fails on master branch.
i cannot add tests right now because `test_remove_categories` in `test_categorical.py` does not fail on my machine. it also passes on a number of travis builds, and fails only on a couple.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8396 | 2014-09-26T14:05:10Z | 2014-09-26T14:44:05Z | null | 2014-09-26T18:32:01Z |
BUG: fix Panel.fillna() ignoring axis parameter | diff --git a/doc/source/whatsnew/v0.15.1.txt b/doc/source/whatsnew/v0.15.1.txt
index e96adc2bd9559..4656c82b0099c 100644
--- a/doc/source/whatsnew/v0.15.1.txt
+++ b/doc/source/whatsnew/v0.15.1.txt
@@ -227,3 +227,5 @@ Bug Fixes
- Fixed a bug where plotting a column ``y`` and specifying a label would mutate the index name of the original DataFrame (:issue:`8494`)
- Bug in ``date_range`` where partially-specified dates would incorporate current date (:issue:`6961`)
+
+- Fixed a bug that prevented setting values in a mixed-type Panel4D
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 71668a73d9286..a1ddff009006d 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -21,10 +21,14 @@
from pandas.core.common import (isnull, notnull, is_list_like,
_values_from_object, _maybe_promote,
_maybe_box_datetimelike, ABCSeries,
- SettingWithCopyError, SettingWithCopyWarning)
+ SettingWithCopyError, SettingWithCopyWarning,
+ CategoricalDtype)
import pandas.core.nanops as nanops
from pandas.util.decorators import Appender, Substitution, deprecate_kwarg
from pandas.core import config
+from pandas.core.categorical import Categorical
+
+from itertools import product
# goal is to be able to define the docs close to function, while still being
# able to share
@@ -2237,25 +2241,24 @@ def convert_objects(self, convert_dates=True, convert_numeric=False,
#----------------------------------------------------------------------
# Filling NA's
- def fillna(self, value=None, method=None, axis=0, inplace=False,
+ def fillna(self, value=None, method=None, axis=None, inplace=False,
limit=None, downcast=None):
"""
Fill NA/NaN values using the specified method
Parameters
----------
- method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
- Method to use for filling holes in reindexed Series
- pad / ffill: propagate last valid observation forward to next valid
- backfill / bfill: use NEXT valid observation to fill gap
value : scalar, dict, Series, or DataFrame
Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of
values specifying which value to use for each index (for a Series) or
column (for a DataFrame). (values not in the dict/Series/DataFrame will not be
filled). This value cannot be a list.
- axis : {0, 1}, default 0
- * 0: fill column-by-column
- * 1: fill row-by-row
+ method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
+ Method to use for filling holes in reindexed Series
+ pad / ffill: propagate last valid observation forward to next valid
+ backfill / bfill: use NEXT valid observation to fill gap
+ axis : {0, 1, 2, 3}, defaults to the stat axis
+ The stat axis is 0 for Series and DataFrame, 1 for Panel, and 2 for Panel4D
inplace : boolean, default False
If True, fill in place. Note: this will modify any
other views on this object, (e.g. a no-copy slice for a column in a
@@ -2263,7 +2266,7 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
limit : int, default None
Maximum size gap to forward or backward fill
downcast : dict, default is None
- a dict of item->dtype of what to downcast if possible,
+ A dict of item->dtype of what to downcast if possible,
or the string 'infer' which will try to downcast to an appropriate
equal type (e.g. float64 to int64 if possible)
@@ -2275,54 +2278,47 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
-------
filled : same type as caller
"""
- if isinstance(value, (list, tuple)):
- raise TypeError('"value" parameter must be a scalar or dict, but '
- 'you passed a "{0}"'.format(type(value).__name__))
self._consolidate_inplace()
- axis = self._get_axis_number(axis)
- method = com._clean_fill_method(method)
+ if axis is None:
+ axis = self._stat_axis_number
+ else:
+ axis = self._get_axis_number(axis)
from pandas import DataFrame
if value is None:
if method is None:
raise ValueError('must specify a fill method or value')
- if self._is_mixed_type and axis == 1:
- if inplace:
- raise NotImplementedError()
- result = self.T.fillna(method=method, limit=limit).T
-
- # need to downcast here because of all of the transposes
- result._data = result._data.downcast()
- return result
-
- # > 3d
- if self.ndim > 3:
- raise NotImplementedError(
- 'Cannot fillna with a method for > 3dims'
- )
-
- # 3d
- elif self.ndim == 3:
+ method = com._clean_fill_method(method)
- # fill in 2d chunks
- result = dict([(col, s.fillna(method=method, value=value))
- for col, s in compat.iteritems(self)])
- return self._constructor.from_dict(result).__finalize__(self)
+ off_axes = list(range(self.ndim))
+ off_axes.remove(axis)
+ expanded = [list(range(self.shape[x])) for x in off_axes]
+ frame = self if inplace else self.copy()
+ for axes_prod in product(*expanded):
+ slicer = list(axes_prod)
+ slicer.insert(axis, slice(None))
+ sl = tuple(slicer)
+ piece = frame.iloc[sl]
+ new_data = piece._data.interpolate(method=method,
+ limit=limit,
+ inplace=True,
+ coerce=True)
+ frame.iloc[sl] = piece._constructor(new_data)
+
+ new_data = frame._data
+ if downcast:
+ new_data = new_data.downcast(dtypes=downcast)
- # 2d or less
- method = com._clean_fill_method(method)
- new_data = self._data.interpolate(method=method,
- axis=axis,
- limit=limit,
- inplace=inplace,
- coerce=True,
- downcast=downcast)
else:
if method is not None:
raise ValueError('cannot specify both a fill method and value')
+ if isinstance(value, (list, tuple)):
+ raise TypeError('"value" parameter must be a scalar or dict, but '
+ 'you passed a "{0}"'.format(type(value).__name__))
+
if len(self._get_axis(axis)) == 0:
return self
@@ -2368,12 +2364,12 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
else:
return self._constructor(new_data).__finalize__(self)
- def ffill(self, axis=0, inplace=False, limit=None, downcast=None):
+ def ffill(self, axis=None, inplace=False, limit=None, downcast=None):
"Synonym for NDFrame.fillna(method='ffill')"
return self.fillna(method='ffill', axis=axis, inplace=inplace,
limit=limit, downcast=downcast)
- def bfill(self, axis=0, inplace=False, limit=None, downcast=None):
+ def bfill(self, axis=None, inplace=False, limit=None, downcast=None):
"Synonym for NDFrame.fillna(method='bfill')"
return self.fillna(method='bfill', axis=axis, inplace=inplace,
limit=limit, downcast=downcast)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 954acb0f95159..e6f91d2ae6f44 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -355,7 +355,7 @@ def _setitem_with_indexer(self, indexer, value):
# if we have a partial multiindex, then need to adjust the plane
# indexer here
if (len(labels) == 1 and
- isinstance(self.obj[labels[0]].index, MultiIndex)):
+ isinstance(self.obj[labels[0]].axes[0], MultiIndex)):
item = labels[0]
obj = self.obj[item]
index = obj.index
@@ -421,7 +421,7 @@ def can_do_equal_len():
l = len(value)
item = labels[0]
- index = self.obj[item].index
+ index = self.obj[item].axes[0]
# equal len list/ndarray
if len(index) == l:
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 14e4e32acae9f..c70d2b599e038 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -1356,20 +1356,90 @@ def test_fillna(self):
assert_frame_equal(filled['ItemA'],
panel['ItemA'].fillna(method='backfill'))
+ # Fill forward.
+ filled = self.panel.fillna(method='ffill')
+ assert_frame_equal(filled['ItemA'],
+ self.panel['ItemA'].fillna(method='ffill'))
+
+ # With limit.
+ filled = self.panel.fillna(method='backfill', limit=1)
+ assert_frame_equal(filled['ItemA'],
+ self.panel['ItemA'].fillna(method='backfill', limit=1))
+
+ # With downcast.
+ rounded = self.panel.apply(lambda x: x.apply(np.round))
+ filled = rounded.fillna(method='backfill', downcast='infer')
+ assert_frame_equal(filled['ItemA'],
+ rounded['ItemA'].fillna(method='backfill', downcast='infer'))
+
+ # Now explicitly request axis 1.
+ filled = self.panel.fillna(method='backfill', axis=1)
+ assert_frame_equal(filled['ItemA'],
+ self.panel['ItemA'].fillna(method='backfill', axis=0))
+
+ # Fill along axis 2, equivalent to filling along axis 1 of each
+ # DataFrame.
+ filled = self.panel.fillna(method='backfill', axis=2)
+ assert_frame_equal(filled['ItemA'],
+ self.panel['ItemA'].fillna(method='backfill', axis=1))
+
+ # Fill an empty panel.
empty = self.panel.reindex(items=[])
filled = empty.fillna(0)
assert_panel_equal(filled, empty)
+ # either method or value must be specified
self.assertRaises(ValueError, self.panel.fillna)
+ # method and value can not both be specified
self.assertRaises(ValueError, self.panel.fillna, 5, method='ffill')
+ # can't pass list or tuple, only scalar
self.assertRaises(TypeError, self.panel.fillna, [1, 2])
self.assertRaises(TypeError, self.panel.fillna, (1, 2))
# limit not implemented when only value is specified
p = Panel(np.random.randn(3,4,5))
p.iloc[0:2,0:2,0:2] = np.nan
- self.assertRaises(NotImplementedError, lambda : p.fillna(999,limit=1))
+ self.assertRaises(NotImplementedError, lambda : p.fillna(999, limit=1))
+
+ def test_fillna_axis_0(self):
+ # GH 8395
+
+ # Forward fill along axis 0, interpolating values across DataFrames.
+ filled = self.panel.fillna(method='ffill', axis=0)
+ nan_indexes = self.panel['ItemB']['C'].index[
+ self.panel['ItemB']['C'].apply(np.isnan)]
+
+ # Values from ItemA are filled into ItemB.
+ assert_series_equal(filled['ItemB']['C'][nan_indexes],
+ self.panel['ItemA']['C'][nan_indexes])
+
+ # Backfill along axis 0.
+ filled = self.panel.fillna(method='backfill', axis=0)
+
+ # The test data lacks values that can be backfilled on axis 0.
+ assert_panel_equal(filled, self.panel)
+
+ # Reverse the panel and backfill along axis 0, to properly test
+ # backfill.
+ reverse_panel = self.panel.reindex_axis(reversed(self.panel.axes[0]))
+ filled = reverse_panel.fillna(method='bfill', axis=0)
+ nan_indexes = reverse_panel['ItemB']['C'].index[
+ reverse_panel['ItemB']['C'].apply(np.isnan)]
+ assert_series_equal(filled['ItemB']['C'][nan_indexes],
+ reverse_panel['ItemA']['C'][nan_indexes])
+
+ # Fill along axis 0 with limit.
+ filled = self.panel.fillna(method='ffill', axis=0, limit=1)
+ a_nan = self.panel['ItemA']['C'].index[
+ self.panel['ItemA']['C'].apply(np.isnan)]
+ b_nan = self.panel['ItemB']['C'].index[
+ self.panel['ItemB']['C'].apply(np.isnan)]
+
+ # Cells that are nan in ItemB but not in ItemA remain unfilled in
+ # ItemC.
+ self.assertTrue(
+ filled['ItemC']['C'][b_nan.diff(a_nan)].apply(np.isnan).all())
def test_ffill_bfill(self):
assert_panel_equal(self.panel.ffill(),
diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py
index e88a8c3b2874c..4837b94fe3d53 100644
--- a/pandas/tests/test_panel4d.py
+++ b/pandas/tests/test_panel4d.py
@@ -845,11 +845,107 @@ def test_sort_index(self):
# assert_panel_equal(sorted_panel, self.panel)
def test_fillna(self):
+ # GH 8395
self.assertFalse(np.isfinite(self.panel4d.values).all())
filled = self.panel4d.fillna(0)
self.assertTrue(np.isfinite(filled.values).all())
- self.assertRaises(NotImplementedError, self.panel4d.fillna, method='pad')
+ filled = self.panel4d.fillna(method='backfill')
+ assert_frame_equal(filled['l1']['ItemA'],
+ self.panel4d['l1']['ItemA'].fillna(method='backfill'))
+
+ panel4d = self.panel4d.copy()
+ panel4d['str'] = 'foo'
+
+ filled = panel4d.fillna(method='backfill')
+ assert_frame_equal(filled['l1']['ItemA'],
+ panel4d['l1']['ItemA'].fillna(method='backfill'))
+
+ # Fill forward.
+ filled = self.panel4d.fillna(method='ffill')
+ assert_frame_equal(filled['l1']['ItemA'],
+ self.panel4d['l1']['ItemA'].fillna(method='ffill'))
+
+ # With limit.
+ filled = self.panel4d.fillna(method='backfill', limit=1)
+ assert_frame_equal(filled['l1']['ItemA'],
+ self.panel4d['l1']['ItemA'].fillna(method='backfill', limit=1))
+
+ # With downcast.
+ rounded = self.panel4d.apply(lambda x: x.apply(np.round))
+ filled = rounded.fillna(method='backfill', downcast='infer')
+ assert_frame_equal(filled['l1']['ItemA'],
+ rounded['l1']['ItemA'].fillna(method='backfill', downcast='infer'))
+
+ # Now explicitly request axis 2.
+ filled = self.panel4d.fillna(method='backfill', axis=2)
+ assert_frame_equal(filled['l1']['ItemA'],
+ self.panel4d['l1']['ItemA'].fillna(method='backfill', axis=0))
+
+ # Fill along axis 3, equivalent to filling along axis 1 of each
+ # DataFrame.
+ filled = self.panel4d.fillna(method='backfill', axis=3)
+ assert_frame_equal(filled['l1']['ItemA'],
+ self.panel4d['l1']['ItemA'].fillna(method='backfill', axis=1))
+
+ # Fill an empty panel.
+ empty = self.panel4d.reindex(items=[])
+ filled = empty.fillna(0)
+ assert_panel4d_equal(filled, empty)
+
+ # either method or value must be specified
+ self.assertRaises(ValueError, self.panel4d.fillna)
+ # method and value can not both be specified
+ self.assertRaises(ValueError, self.panel4d.fillna, 5, method='ffill')
+
+ # can't pass list or tuple, only scalar
+ self.assertRaises(TypeError, self.panel4d.fillna, [1, 2])
+ self.assertRaises(TypeError, self.panel4d.fillna, (1, 2))
+
+ # limit not implemented when only value is specified
+ p = Panel4D(np.random.randn(3,4,5,6))
+ p.iloc[0:2,0:2,0:2,0:2] = np.nan
+ self.assertRaises(NotImplementedError, lambda : p.fillna(999, limit=1))
+
+ def test_fillna_axis_0(self):
+ # GH 8395
+
+ # Back fill along axis 0, interpolating values across Panels
+ filled = self.panel4d.fillna(method='bfill', axis=0)
+ nan_indexes = self.panel4d['l1']['ItemB']['C'].index[
+ self.panel4d['l1']['ItemB']['C'].apply(np.isnan)]
+
+ # Values from ItemC are filled into ItemB.
+ assert_series_equal(filled['l1']['ItemB']['C'][nan_indexes],
+ self.panel4d['l1']['ItemC']['C'][nan_indexes])
+
+ # Forward fill along axis 0.
+ filled = self.panel4d.fillna(method='ffill', axis=0)
+
+ # The test data lacks values that can be backfilled on axis 0.
+ assert_panel4d_equal(filled, self.panel4d)
+
+ # Reverse the panel and backfill along axis 0, to properly test
+ # forward fill.
+ reverse_panel = self.panel4d.reindex_axis(reversed(self.panel4d.axes[0]))
+ filled = reverse_panel.fillna(method='ffill', axis=0)
+ nan_indexes = reverse_panel['l3']['ItemB']['C'].index[
+ reverse_panel['l3']['ItemB']['C'].apply(np.isnan)]
+ assert_series_equal(filled['l3']['ItemB']['C'][nan_indexes],
+ reverse_panel['l1']['ItemB']['C'][nan_indexes])
+
+ # Fill along axis 0 with limit.
+ filled = self.panel4d.fillna(method='bfill', axis=0, limit=1)
+ c_nan = self.panel4d['l1']['ItemC']['C'].index[
+ self.panel4d['l1']['ItemC']['C'].apply(np.isnan)]
+ b_nan = self.panel4d['l1']['ItemB']['C'].index[
+ self.panel4d['l1']['ItemB']['C'].apply(np.isnan)]
+
+ # Cells that are nan in ItemB but not in ItemC remain unfilled in
+ # ItemA.
+ self.assertTrue(
+ filled['l1']['ItemA']['C'][b_nan.diff(c_nan)].apply(np.isnan).all())
+
def test_swapaxes(self):
result = self.panel4d.swapaxes('labels', 'items')
| This fixes #8251. It may need some more comprehensive tests but before I go too much farther I want to make sure the axis numbering scheme makes sense . The default behavior of `fillna` is to fill along `axis=0`. In the case of a DataFrame this fills along the columns. However, in the case of a Panel, filling along `axis=0` means you're filling along items. I'm not sure if that's the behavior that most users would think is the default. You might note that I also removed the references to what the behavior of each axis value is in the docstring since it gets a bit arbitrary when you consider both DataFrames and Panels.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8395 | 2014-09-26T05:26:38Z | 2015-07-12T14:58:11Z | null | 2022-10-13T00:16:09Z |
BUG: apply mask to aligned new values | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 8c0e193ec6348..752fac2532dac 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -985,3 +985,4 @@ Bug Fixes
- Bug in OLS where running with "cluster" and "nw_lags" parameters did not work correctly, but also did not throw an error
(:issue:`5884').
- Bug in ``DataFrame.dropna`` that interpreted non-existent columns in the subset argument as the 'last column' (:issue:`8303`)
+- Bug in masked series assignment where mismatching types would break alignment (:issue:`8387`)
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 0055947c59210..354ccd2c94583 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -3924,14 +3924,16 @@ def _putmask_smart(v, m, n):
Parameters
----------
- v : array_like
- m : array_like
- n : array_like
+ v : `values`, updated in-place (array like)
+ m : `mask`, applies to both sides (array like)
+ n : `new values` either scalar or an array like aligned with `values`
"""
# n should be the length of the mask or a scalar here
if not is_list_like(n):
n = np.array([n] * len(m))
+ elif isinstance(n, np.ndarray) and n.ndim == 0: # numpy scalar
+ n = np.repeat(np.array(n, ndmin=1), len(m))
# see if we are only masking values that if putted
# will work in the current dtype
@@ -3949,10 +3951,10 @@ def _putmask_smart(v, m, n):
dtype, _ = com._maybe_promote(n.dtype)
nv = v.astype(dtype)
try:
- nv[m] = n
+ nv[m] = n[m]
except ValueError:
idx, = np.where(np.squeeze(m))
- for mask_index, new_val in zip(idx, n):
+ for mask_index, new_val in zip(idx, n[m]):
nv[mask_index] = new_val
return nv
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 0b863f9662e14..3694393fbd978 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -5014,6 +5014,14 @@ def test_cast_on_putmask(self):
assert_series_equal(s, expected)
+ def test_type_promote_putmask(self):
+ # GH8387: test that changing types does not break alignment
+ ts = Series(np.random.randn(100), index=np.arange(100,0,-1)).round(5)
+ left, mask = ts.copy(), ts > 0
+ right = ts[mask].copy().map(str)
+ left[mask] = right
+ assert_series_equal(left, ts.map(lambda t: str(t) if t > 0 else t))
+
def test_astype_cast_nan_int(self):
df = Series([1.0, 2.0, 3.0, np.nan])
self.assertRaises(ValueError, df.astype, np.int64)
@@ -6286,4 +6294,3 @@ def test_unique_data_ownership(self):
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
exit=False)
-
| closes https://github.com/pydata/pandas/issues/8387
| https://api.github.com/repos/pandas-dev/pandas/pulls/8394 | 2014-09-26T03:27:22Z | 2014-09-29T15:19:28Z | null | 2014-10-01T00:32:59Z |
TST: Fix failing pie plot tests | diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 7e9b562ba0014..fac6a4d83e13b 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -635,7 +635,7 @@ def test_pie_series(self):
series = Series([1, 2, np.nan, 4],
index=['a', 'b', 'c', 'd'], name='YLABEL')
ax = _check_plot_works(series.plot, kind='pie')
- self._check_text_labels(ax.texts, series.index)
+ self._check_text_labels(ax.texts, ['a', 'b', '', 'd'])
def test_pie_nan(self):
s = Series([1, np.nan, 1, 1])
@@ -2798,13 +2798,17 @@ def test_pie_df_nan(self):
base_expected = ['0', '1', '2', '3']
for i, ax in enumerate(axes):
- expected = list(base_expected) # copy
+ expected = list(base_expected) # force copy
expected[i] = ''
result = [x.get_text() for x in ax.texts]
self.assertEqual(result, expected)
# legend labels
- self.assertEqual([x.get_text() for x in ax.get_legend().get_texts()],
- base_expected)
+ # NaN's not included in legend with subplots
+ # see https://github.com/pydata/pandas/issues/8390
+ self.assertEqual([x.get_text() for x in
+ ax.get_legend().get_texts()],
+ base_expected[:i] + base_expected[i+1:])
+
def test_errorbar_plot(self):
d = {'x': np.arange(12), 'y': np.arange(12, 0, -1)}
df = DataFrame(d)
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 7b295d9dd8fb8..0b1a0ceb8da60 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -2058,8 +2058,11 @@ def blank_labeler(label, value):
# labels is used for each wedge's labels
# Blank out labels for values of 0 so they don't overlap
# with nonzero wedges
- blabels = [blank_labeler(label, value) for
- label, value in zip(labels, y)]
+ if labels is not None:
+ blabels = [blank_labeler(label, value) for
+ label, value in zip(labels, y)]
+ else:
+ blabels = None
results = ax.pie(y, labels=blabels, **kwds)
if kwds.get('autopct', None) is not None:
| Fixes the build failures from merging https://github.com/pydata/pandas/pull/8307
| https://api.github.com/repos/pandas-dev/pandas/pulls/8393 | 2014-09-25T18:41:16Z | 2014-09-25T19:46:38Z | 2014-09-25T19:46:38Z | 2017-04-05T02:05:56Z |
DOC: Use square figsize for pie plots | diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst
index adbecbe688945..3285efadf8ad1 100644
--- a/doc/source/visualization.rst
+++ b/doc/source/visualization.rst
@@ -621,7 +621,11 @@ A ``ValueError`` will be raised if there are any negative values in your data.
series = Series(3 * rand(4), index=['a', 'b', 'c', 'd'], name='series')
@savefig series_pie_plot.png
- series.plot(kind='pie')
+ series.plot(kind='pie', figsize=(6, 6))
+
+For pie plots it's best to use square figures, one's with an equal aspect ratio. You can create the
+figure with equal width and height, or force the aspect ratio to be equal after plotting by
+calling ``ax.set_aspect('equal')`` on the returned ``axes`` object.
Note that pie plot with :class:`DataFrame` requires that you either specify a target column by the ``y``
argument or ``subplots=True``. When ``y`` is specified, pie plot of selected column
@@ -639,7 +643,7 @@ A legend will be drawn in each pie plots by default; specify ``legend=False`` to
df = DataFrame(3 * rand(4, 2), index=['a', 'b', 'c', 'd'], columns=['x', 'y'])
@savefig df_pie_plot.png
- df.plot(kind='pie', subplots=True)
+ df.plot(kind='pie', subplots=True, figsize=(8, 4))
You can use the ``labels`` and ``colors`` keywords to specify the labels and colors of each wedge.
@@ -662,7 +666,7 @@ Also, other keywords supported by :func:`matplotlib.pyplot.pie` can be used.
@savefig series_pie_plot_options.png
series.plot(kind='pie', labels=['AA', 'BB', 'CC', 'DD'], colors=['r', 'g', 'b', 'c'],
- autopct='%.2f', fontsize=20)
+ autopct='%.2f', fontsize=20, figsize=(6, 6))
If you pass values whose sum total is less than 1.0, matplotlib draws a semicircle.
@@ -676,7 +680,7 @@ If you pass values whose sum total is less than 1.0, matplotlib draws a semicirc
series = Series([0.1] * 4, index=['a', 'b', 'c', 'd'], name='series2')
@savefig series_pie_plot_semi.png
- series.plot(kind='pie')
+ series.plot(kind='pie', figsize=(6, 6))
See the `matplotlib pie documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pie>`__ for more.
@@ -1113,16 +1117,16 @@ or columns needed, given the other.
.. ipython:: python
@savefig frame_plot_subplots_layout.png
- df.plot(subplots=True, layout=(2, 3), figsize=(6, 6));
+ df.plot(subplots=True, layout=(3, 2), figsize=(6, 6), sharex=False);
The above example is identical to using
.. ipython:: python
- df.plot(subplots=True, layout=(-1, 3), figsize=(6, 6));
+ df.plot(subplots=True, layout=(3, -1), figsize=(6, 6), sharex=False);
-The required number of rows (2) is inferred from the number of series to plot
-and the given number of columns (3).
+The required number of columns (2) is inferred from the number of series to plot
+and the given number of rows (3).
Also, you can pass multiple axes created beforehand as list-like via ``ax`` keyword.
This allows to use more complicated layout.
| First commit closes https://github.com/pydata/pandas/issues/8308
second closes https://github.com/pydata/pandas/issues/8312 aside from using mpl 1.4 to build the docs.
I can post any examples if you want.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8391 | 2014-09-25T17:06:53Z | 2014-10-04T18:01:29Z | 2014-10-04T18:01:29Z | 2015-08-18T12:44:59Z |
EHN: Allow DataFrame.fillna to accept a DataFrame as its fill value. | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 92eb1d54ae676..5e7d4947aecea 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -278,7 +278,7 @@ API changes
- ``DataFrame.info()`` now ends its output with a newline character (:issue:`8114`)
- add ``copy=True`` argument to ``pd.concat`` to enable pass thrue of complete blocks (:issue:`8252`)
-- ``.fillna`` will now raise a ``NotImplementedError`` when passed a ``DataFrame`` (:issue:`8377`)
+
.. _whatsnew_0150.dt:
@@ -785,7 +785,7 @@ Enhancements
meta-engine that automatically uses whichever version of openpyxl is
installed. (:issue:`7177`)
-
+- ``DataFrame.fillna`` can now accept a ``DataFrame`` as a fill value (:issue:`8377`)
.. _whatsnew_0150.performance:
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 30f2d6bf093f2..9f9b543f0fa7d 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2231,10 +2231,10 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
Method to use for filling holes in reindexed Series
pad / ffill: propagate last valid observation forward to next valid
backfill / bfill: use NEXT valid observation to fill gap
- value : scalar, dict, or Series
- Value to use to fill holes (e.g. 0), alternately a dict/Series of
+ value : scalar, dict, Series, or DataFrame
+ Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of
values specifying which value to use for each index (for a Series) or
- column (for a DataFrame). (values not in the dict/Series will not be
+ column (for a DataFrame). (values not in the dict/Series/DataFrame will not be
filled). This value cannot be a list.
axis : {0, 1}, default 0
* 0: fill column-by-column
@@ -2342,7 +2342,7 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
inplace=inplace,
downcast=downcast)
elif isinstance(value, DataFrame) and self.ndim == 2:
- raise NotImplementedError("can't use fillna with a DataFrame, use .where instead")
+ new_data = self.where(self.notnull(), value)
else:
raise ValueError("invalid fill value with a %s" % type(value))
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 99b1fa09a8d51..84d8c4ac39461 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -7630,6 +7630,29 @@ def test_fillna_dict_series(self):
with assertRaisesRegexp(NotImplementedError, 'column by column'):
df.fillna(df.max(1), axis=1)
+ def test_fillna_dataframe(self):
+ # GH 8377
+ df = DataFrame({'a': [nan, 1, 2, nan, nan],
+ 'b': [1, 2, 3, nan, nan],
+ 'c': [nan, 1, 2, 3, 4]},
+ index = list('VWXYZ'))
+
+ # df2 may have different index and columns
+ df2 = DataFrame({'a': [nan, 10, 20, 30, 40],
+ 'b': [50, 60, 70, 80, 90],
+ 'foo': ['bar']*5},
+ index = list('VWXuZ'))
+
+ result = df.fillna(df2)
+
+ # only those columns and indices which are shared get filled
+ expected = DataFrame({'a': [nan, 1, 2, nan, 40],
+ 'b': [1, 2, 3, nan, 90],
+ 'c': [nan, 1, 2, 3, 4]},
+ index = list('VWXYZ'))
+
+ assert_frame_equal(result, expected)
+
def test_fillna_columns(self):
df = DataFrame(np.random.randn(10, 10))
df.values[:, ::2] = np.nan
@@ -7643,6 +7666,7 @@ def test_fillna_columns(self):
expected = df.astype(float).fillna(method='ffill', axis=1)
assert_frame_equal(result, expected)
+
def test_fillna_invalid_method(self):
with assertRaisesRegexp(ValueError, 'ffil'):
self.frame.fillna(method='ffil')
@@ -7652,8 +7676,6 @@ def test_fillna_invalid_value(self):
self.assertRaises(TypeError, self.frame.fillna, [1, 2])
# tuple
self.assertRaises(TypeError, self.frame.fillna, (1, 2))
- # frame
- self.assertRaises(NotImplementedError, self.frame.fillna, self.frame)
# frame with series
self.assertRaises(ValueError, self.frame.iloc[:,0].fillna, self.frame)
| Related: [SO](http://stackoverflow.com/q/26002564/190597)
Fixes #8377
| https://api.github.com/repos/pandas-dev/pandas/pulls/8388 | 2014-09-25T13:47:28Z | 2014-09-26T15:19:39Z | 2014-09-26T15:19:39Z | 2014-09-26T19:11:04Z |
ENH: add the parameter dropna to the function to_dict. | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 4654ceee9896b..4486c6278e0d3 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -60,6 +60,7 @@
import pandas.algos as _algos
from pandas.core.config import get_option
+from math import isnan
#----------------------------------------------------------------------
# Docstring templates
@@ -640,7 +641,7 @@ def from_dict(cls, data, orient='columns', dtype=None):
return cls(data, index=index, columns=columns, dtype=dtype)
- def to_dict(self, outtype='dict'):
+ def to_dict(self, outtype='dict', dropna=False):
"""
Convert DataFrame to dictionary.
@@ -653,6 +654,8 @@ def to_dict(self, outtype='dict'):
{column -> Series(values)}. `records` returns [{columns -> value}].
Abbreviations are allowed.
+ dropna: boolean, default False
+ drops all NaN elements from the dictionary.
Returns
-------
@@ -661,17 +664,31 @@ def to_dict(self, outtype='dict'):
if not self.columns.is_unique:
warnings.warn("DataFrame columns are not unique, some "
"columns will be omitted.", UserWarning)
- if outtype.lower().startswith('d'):
- return dict((k, v.to_dict()) for k, v in compat.iteritems(self))
- elif outtype.lower().startswith('l'):
- return dict((k, v.tolist()) for k, v in compat.iteritems(self))
- elif outtype.lower().startswith('s'):
- return dict((k, v) for k, v in compat.iteritems(self))
- elif outtype.lower().startswith('r'):
- return [dict((k, v) for k, v in zip(self.columns, row))
- for row in self.values]
- else: # pragma: no cover
- raise ValueError("outtype %s not understood" % outtype)
+ if not dropna:
+ if outtype.lower().startswith('d'):
+ return dict((k, v.to_dict()) for k, v in compat.iteritems(self))
+ elif outtype.lower().startswith('l'):
+ return dict((k, v.tolist()) for k, v in compat.iteritems(self))
+ elif outtype.lower().startswith('s'):
+ return dict((k, v) for k, v in compat.iteritems(self))
+ elif outtype.lower().startswith('r'):
+ return [dict((k, v) for k, v in zip(self.columns, row))
+ for row in self.values]
+ else: # pragma: no cover
+ raise ValueError("outtype %s not understood" % outtype)
+
+ if dropna:
+ if outtype.lower().startswith('d'):
+ return dict((k, v.dropna().to_dict()) for k, v in compat.iteritems(self))
+ elif outtype.lower().startswith('l'):
+ return dict((k, v.dropna().tolist()) for k, v in compat.iteritems(self))
+ elif outtype.lower().startswith('s'):
+ return dict((k, v.dropna()) for k, v in compat.iteritems(self))
+ elif outtype.lower().startswith('r'):
+ return [dict((k, v) for k, v in zip(self.columns, row) if not isnan(v) )
+ for row in self.values]
+ else: # pragma: no cover
+ raise ValueError("outtype %s not understood" % outtype)
def to_gbq(self, destination_table, project_id=None, chunksize=10000,
verbose=True, reauth=False):
| this is usefull because you cant reach the same effect by just using
dropna().to_dict() also see
http://stackoverflow.com/questions/26033301/make-pandas-dataframe-to-a-dict-and-dropna/26033302#26033302
| https://api.github.com/repos/pandas-dev/pandas/pulls/8385 | 2014-09-25T08:49:11Z | 2015-05-09T16:09:38Z | null | 2023-05-11T01:12:39Z |
non-existent columns in DataFrame.dropna subset argument now raises KeyError | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 92eb1d54ae676..7115364fbb0e5 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -971,4 +971,4 @@ Bug Fixes
- Bug in DataFrame terminal display: Setting max_column/max_rows to zero did not trigger auto-resizing of dfs to fit terminal width/height (:issue:`7180`).
- Bug in OLS where running with "cluster" and "nw_lags" parameters did not work correctly, but also did not throw an error
(:issue:`5884').
-
+- Bug in ``DataFrame.dropna`` that interpreted non-existent columns in the subset argument as the 'last column' (:issue:`8303`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 4654ceee9896b..9402d9a6d0685 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2552,7 +2552,11 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None,
agg_obj = self
if subset is not None:
ax = self._get_axis(agg_axis)
- agg_obj = self.take(ax.get_indexer_for(subset),axis=agg_axis)
+ indices = ax.get_indexer_for(subset)
+ check = indices == -1
+ if check.any():
+ raise KeyError(list(np.compress(check,subset)))
+ agg_obj = self.take(indices,axis=agg_axis)
count = agg_obj.count(axis=agg_axis)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 99b1fa09a8d51..4cae0f1d266d7 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -7200,6 +7200,8 @@ def test_dropna_corner(self):
# bad input
self.assertRaises(ValueError, self.frame.dropna, how='foo')
self.assertRaises(TypeError, self.frame.dropna, how=None)
+ # non-existent column - 8303
+ self.assertRaises(KeyError, self.frame.dropna, subset=['A','X'])
def test_dropna_multiple_axes(self):
df = DataFrame([[1, np.nan, 2, 3],
| closes #8303.
Now instead of interpreting a bad column name as the 'last column' of the `DataFrame`, `dropna` will raise a `KeyError` instead. unit test and release note now included.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8384 | 2014-09-25T00:31:10Z | 2014-09-26T14:35:18Z | 2014-09-26T14:35:18Z | 2014-09-26T14:35:25Z |
BUG: floats cannot be ranked with tolerance | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index bbc006b41a433..0603bd4deeafa 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -240,6 +240,7 @@ Bug Fixes
- Bug in ``MultiIndex`` where inserting new keys would fail (:issue:`9250`).
- Bug in ``groupby`` when key space exceeds ``int64`` bounds (:issue:`9096`).
- Bug in ``unstack`` with ``TimedeltaIndex`` or ``DatetimeIndex`` and nulls (:issue:`9491`).
+- Bug in ``rank`` where comparing floats with tolerance will cause inconsistent behaviour (:issue:`8365`).
- Fixed character encoding bug in ``read_stata`` and ``StataReader`` when loading data from a URL (:issue:`9231`).
diff --git a/pandas/algos.pyx b/pandas/algos.pyx
index 316a282b71609..5f68c1ee26e87 100644
--- a/pandas/algos.pyx
+++ b/pandas/algos.pyx
@@ -7,7 +7,6 @@ cimport cython
import_array()
cdef float64_t FP_ERR = 1e-13
-cdef float64_t REL_TOL = 1e-07
cimport util
@@ -136,18 +135,6 @@ cdef _take_2d_object(ndarray[object, ndim=2] values,
return result
-cdef inline bint float64_are_diff(float64_t left, float64_t right):
- cdef double abs_diff, allowed
- if right == MAXfloat64 or right == -MAXfloat64:
- if left == right:
- return False
- else:
- return True
- else:
- abs_diff = fabs(left - right)
- allowed = REL_TOL * fabs(right)
- return abs_diff > allowed
-
def rank_1d_float64(object in_arr, ties_method='average', ascending=True,
na_option='keep', pct=False):
"""
@@ -202,7 +189,7 @@ def rank_1d_float64(object in_arr, ties_method='average', ascending=True,
ranks[argsorted[i]] = nan
continue
count += 1.0
- if i == n - 1 or float64_are_diff(sorted_data[i + 1], val):
+ if i == n - 1 or sorted_data[i + 1] != val:
if tiebreak == TIEBREAK_AVERAGE:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = sum_ranks / dups
@@ -361,7 +348,7 @@ def rank_2d_float64(object in_arr, axis=0, ties_method='average',
ranks[i, argsorted[i, j]] = nan
continue
count += 1.0
- if j == k - 1 or float64_are_diff(values[i, j + 1], val):
+ if j == k - 1 or values[i, j + 1] != val:
if tiebreak == TIEBREAK_AVERAGE:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = sum_ranks / dups
@@ -1087,7 +1074,7 @@ def ewmcov(ndarray[double_t] input_x, ndarray[double_t] input_y,
sum_wt = 1.
sum_wt2 = 1.
old_wt = 1.
-
+
for i from 1 <= i < N:
cur_x = input_x[i]
cur_y = input_y[i]
@@ -1117,7 +1104,7 @@ def ewmcov(ndarray[double_t] input_x, ndarray[double_t] input_y,
elif is_observation:
mean_x = cur_x
mean_y = cur_y
-
+
if nobs >= minp:
if not bias:
numerator = sum_wt * sum_wt
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 1a2fc5a8fc13c..3b7b13fd8ed4f 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -4707,7 +4707,7 @@ def test_rank(self):
assert_series_equal(iranks, exp)
iseries = Series([1e-50, 1e-100, 1e-20, 1e-2, 1e-20+1e-30, 1e-1])
- exp = Series([2, 1, 3.5, 5, 3.5, 6])
+ exp = Series([2, 1, 3, 5, 4, 6.0])
iranks = iseries.rank()
assert_series_equal(iranks, exp)
diff --git a/pandas/tests/test_stats.py b/pandas/tests/test_stats.py
index eaaf89a52c2dc..9acd7c2233b7b 100644
--- a/pandas/tests/test_stats.py
+++ b/pandas/tests/test_stats.py
@@ -44,6 +44,43 @@ def _check(s, expected, method='average'):
series = s if dtype is None else s.astype(dtype)
_check(series, results[method], method=method)
+ def test_rank_methods_series(self):
+ tm.skip_if_no_package('scipy', '0.13', 'scipy.stats.rankdata')
+ from scipy.stats import rankdata
+
+ xs = np.random.randn(9)
+ xs = np.concatenate([xs[i:] for i in range(0, 9, 2)]) # add duplicates
+ np.random.shuffle(xs)
+
+ index = [chr(ord('a') + i) for i in range(len(xs))]
+
+ for vals in [xs, xs + 1e6, xs * 1e-6]:
+ ts = Series(vals, index=index)
+
+ for m in ['average', 'min', 'max', 'first', 'dense']:
+ result = ts.rank(m)
+ sprank = rankdata(vals, m if m != 'first' else 'ordinal')
+ tm.assert_series_equal(result, Series(sprank, index=index))
+
+ def test_rank_methods_frame(self):
+ tm.skip_if_no_package('scipy', '0.13', 'scipy.stats.rankdata')
+ from scipy.stats import rankdata
+
+ xs = np.random.randint(0, 21, (100, 26))
+ xs = (xs - 10.0) / 10.0
+ cols = [chr(ord('z') - i) for i in range(xs.shape[1])]
+
+ for vals in [xs, xs + 1e6, xs * 1e-6]:
+ df = DataFrame(vals, columns=cols)
+
+ for ax in [0, 1]:
+ for m in ['average', 'min', 'max', 'first', 'dense']:
+ result = df.rank(axis=ax, method=m)
+ sprank = np.apply_along_axis(rankdata, ax, vals,
+ m if m != 'first' else 'ordinal')
+ expected = DataFrame(sprank, columns=cols)
+ tm.assert_frame_equal(result, expected)
+
def test_rank_dense_method(self):
dtypes = ['O', 'f8', 'i8']
in_out = [([1], [1]),
| closes https://github.com/pydata/pandas/issues/8365
using tolerance in ranking floats can result in inconsistent behavior; currently on master:
```
>>> pd.Series([1001, 1001.0002]).rank()
0 1
1 2
dtype: float64
>>> pd.Series([1001, 1001.0001, 1001.0002]).rank()
0 2
1 2
2 2
dtype: float64
```
so, in effect `1001 == 1001.0002` if one takes small steps in between.
on branch:
```
>>> pd.Series([1001, 1001.0002]).rank()
0 1
1 2
dtype: float64
>>> pd.Series([1001, 1001.0001, 1001.0002]).rank()
0 1
1 2
2 3
dtype: float64
```
original issue(https://github.com/pydata/pandas/issues/8365):
```
>>> from scipy import stats
>>> ts = pd.Series([1000.000669 , 1000.000041 , 1000.000059 , 1000.000063 , 1000.000121 , 1000.000104 , 1000.000040 , 1000.000062 , 1000.000095 , 1000.000091 , 1000.000050 , 1000.000074 , 1000.000063 , 1000.000076 , 1000.000083 , 1000.000061 , 1000.000030 , 1000.000069 , 1000.000090 , 1000.000116 , 1000.000058 , 1000.000074 , 1000.000035 , 1000.000084 , 1000.000067 , 1000.000072 , 1000.000105 , 1000.000091 , 1000.000077 , 1000.000040 , 1000.000108 , 1000.000117 , 1000.000114 , 1000.000117 , 1000.000099 , 1000.000039 , 1000.000046 , 1000.000105 , 1000.000057])
>>> np.all(ts.rank() == stats.rankdata(ts))
True
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/8379 | 2014-09-24T01:40:16Z | 2015-03-03T01:15:35Z | 2015-03-03T01:15:35Z | 2015-03-05T12:47:34Z |
API: .fillna will now raise a NotImplementedError when passed a DataFrame (GH8377) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 1e52d7e20046e..92eb1d54ae676 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -278,6 +278,8 @@ API changes
- ``DataFrame.info()`` now ends its output with a newline character (:issue:`8114`)
- add ``copy=True`` argument to ``pd.concat`` to enable pass thrue of complete blocks (:issue:`8252`)
+- ``.fillna`` will now raise a ``NotImplementedError`` when passed a ``DataFrame`` (:issue:`8377`)
+
.. _whatsnew_0150.dt:
.dt accessor
@@ -956,7 +958,6 @@ Bug Fixes
- Bug with stacked barplots and NaNs (:issue:`8175`).
-
- Bug in interpolation methods with the ``limit`` keyword when no values needed interpolating (:issue:`7173`).
- Bug where ``col_space`` was ignored in ``DataFrame.to_string()`` when ``header=False`` (:issue:`8230`).
- Bug with ``DatetimeIndex.asof`` incorrectly matching partial strings and returning the wrong date (:issue:`8245`).
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index c9f83bfe07116..30f2d6bf093f2 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2266,6 +2266,7 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
axis = self._get_axis_number(axis)
method = com._clean_fill_method(method)
+ from pandas import DataFrame
if value is None:
if method is None:
raise ValueError('must specify a fill method or value')
@@ -2308,10 +2309,14 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
if len(self._get_axis(axis)) == 0:
return self
- if self.ndim == 1 and value is not None:
+ if self.ndim == 1:
if isinstance(value, (dict, com.ABCSeries)):
from pandas import Series
value = Series(value)
+ elif not com.is_list_like(value):
+ pass
+ else:
+ raise ValueError("invalid fill value with a %s" % type(value))
new_data = self._data.fillna(value=value,
limit=limit,
@@ -2331,11 +2336,15 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
obj = result[k]
obj.fillna(v, limit=limit, inplace=True)
return result
- else:
+ elif not com.is_list_like(value):
new_data = self._data.fillna(value=value,
limit=limit,
inplace=inplace,
downcast=downcast)
+ elif isinstance(value, DataFrame) and self.ndim == 2:
+ raise NotImplementedError("can't use fillna with a DataFrame, use .where instead")
+ else:
+ raise ValueError("invalid fill value with a %s" % type(value))
if inplace:
self._update_inplace(new_data)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 18de6ac35bf9c..03dbfbbf1fd6c 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -7650,6 +7650,10 @@ def test_fillna_invalid_value(self):
self.assertRaises(TypeError, self.frame.fillna, [1, 2])
# tuple
self.assertRaises(TypeError, self.frame.fillna, (1, 2))
+ # frame
+ self.assertRaises(NotImplementedError, self.frame.fillna, self.frame)
+ # frame with series
+ self.assertRaises(ValueError, self.frame.iloc[:,0].fillna, self.frame)
def test_replace_inplace(self):
self.tsframe['A'][:5] = nan
| xref #8377
| https://api.github.com/repos/pandas-dev/pandas/pulls/8378 | 2014-09-23T23:24:28Z | 2014-09-24T11:59:42Z | 2014-09-24T11:59:42Z | 2014-09-24T11:59:42Z |
BUG: Intersection buggy for non-monotonic non-unique indices (GH8362) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 1e52d7e20046e..02f6b2531a969 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -970,4 +970,5 @@ Bug Fixes
- Bug in DataFrame terminal display: Setting max_column/max_rows to zero did not trigger auto-resizing of dfs to fit terminal width/height (:issue:`7180`).
- Bug in OLS where running with "cluster" and "nw_lags" parameters did not work correctly, but also did not throw an error
(:issue:`5884').
+- Bug in Index.intersection on non-monotonic non-unique indexes (:issue:`8362`).
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 23f4cfd442a59..f3070ffcbce7b 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -1279,6 +1279,7 @@ def intersection(self, other):
except:
# duplicates
indexer = self.get_indexer_non_unique(other.values)[0].unique()
+ indexer = indexer[indexer != -1]
taken = self.take(indexer)
if self.name != other.name:
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index baa8f6411393e..3001c4f09d982 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -532,6 +532,13 @@ def test_intersection(self):
result3 = idx1.intersection(idx3)
self.assertTrue(tm.equalContents(result3, expected3))
self.assertEqual(result3.name, expected3.name)
+
+ # non-monotonic non-unique
+ idx1 = Index(['A','B','A','C'])
+ idx2 = Index(['B','D'])
+ expected = Index(['B'], dtype='object')
+ result = idx1.intersection(idx2)
+ self.assertTrue(result.equals(expected))
def test_union(self):
first = self.strIndex[5:20]
| Fixes intersection bug in the case of non-monotonic non-unique indexes.
closes #8362
| https://api.github.com/repos/pandas-dev/pandas/pulls/8374 | 2014-09-23T19:01:12Z | 2014-09-29T14:27:54Z | null | 2014-09-29T14:28:06Z |
ENH: Added file path existence check for read_hdf | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 1e52d7e20046e..b1e6fbe0b02bf 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -255,6 +255,8 @@ API changes
- ``Series.to_csv()`` now returns a string when ``path=None``, matching the behaviour of ``DataFrame.to_csv()`` (:issue:`8215`).
+-``read_hdf`` now raises IOError properly when a file that doesn't exist is passed in. Previously, a new, empty file was created, read and stored in an HDFStore object (:issue `7715`).
+
.. _whatsnew_0150.index_set_ops:
- The Index set operations ``+`` and ``-`` were deprecated in order to provide these for numeric type operations on certain index types. ``+`` can be replace by ``.union()`` or ``|``, and ``-`` by ``.difference()``. Further the method name ``Index.diff()`` is deprecated and can be replaced by ``Index.difference()`` (:issue:`8226`)
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 5a68cb16f058f..85edb25a4f38a 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -332,6 +332,16 @@ def read_hdf(path_or_buf, key, **kwargs):
key, auto_close=auto_close, **kwargs)
if isinstance(path_or_buf, string_types):
+
+ try:
+ exists = os.path.exists(path_or_buf)
+
+ #if filepath is too long
+ except (TypeError,ValueError):
+ exists = False
+
+ if not exists:
+ raise IOError('File %s does not exist' % path_or_buf)
# can't auto open/close if we are using an iterator
# so delegate to the iterator
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 4f72c0d1c6cbe..a569823b1f4ce 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -288,6 +288,10 @@ def test_api(self):
self.assertRaises(TypeError, df.to_hdf, path,'df',append=True,format='foo')
self.assertRaises(TypeError, df.to_hdf, path,'df',append=False,format='bar')
+ #File path doesn't exist
+ path = ""
+ self.assertRaises(IOError, read_hdf, path, 'df')
+
def test_api_default_format(self):
# default_format option
| closes #7715
Added simple check for file path existence. It might be more advisable to deprecate this function and separate file buffer and file path read functionality, but the current form matches the rest of the API.
I wasn't sure if there was any tests I needed to add, but if there is, let me know.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8373 | 2014-09-23T19:00:22Z | 2014-09-26T22:06:18Z | 2014-09-26T22:06:18Z | 2014-09-26T22:06:29Z |
BUG: bug in non-evently divisible offsets when resampling (e.g. '7s') (GH8371) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index 1e52d7e20046e..5504ddcce6cbf 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -954,7 +954,7 @@ Bug Fixes
- Bug with kde plot and NaNs (:issue:`8182`)
- Bug in ``GroupBy.count`` with float32 data type were nan values were not excluded (:issue:`8169`).
- Bug with stacked barplots and NaNs (:issue:`8175`).
-
+- Bug in resample with non evenly divisible offsets (e.g. '7s') (:issue:`8371`)
- Bug in interpolation methods with the ``limit`` keyword when no values needed interpolating (:issue:`7173`).
diff --git a/pandas/tseries/resample.py b/pandas/tseries/resample.py
index aa72113cba475..b362c55b156a4 100644
--- a/pandas/tseries/resample.py
+++ b/pandas/tseries/resample.py
@@ -6,7 +6,7 @@
from pandas.tseries.frequencies import to_offset, is_subperiod, is_superperiod
from pandas.tseries.index import DatetimeIndex, date_range
from pandas.tseries.tdi import TimedeltaIndex
-from pandas.tseries.offsets import DateOffset, Tick, _delta_to_nanoseconds
+from pandas.tseries.offsets import DateOffset, Tick, Day, _delta_to_nanoseconds
from pandas.tseries.period import PeriodIndex, period_range
import pandas.tseries.tools as tools
import pandas.core.common as com
@@ -385,9 +385,11 @@ def _get_range_edges(first, last, offset, closed='left', base=0):
offset = to_offset(offset)
if isinstance(offset, Tick):
+ is_day = isinstance(offset, Day)
day_nanos = _delta_to_nanoseconds(timedelta(1))
+
# #1165
- if (day_nanos % offset.nanos) == 0:
+ if (is_day and day_nanos % offset.nanos == 0) or not is_day:
return _adjust_dates_anchored(first, last, offset,
closed=closed, base=base)
diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py
index bafba847257f0..bd6c1766cfd61 100644
--- a/pandas/tseries/tests/test_resample.py
+++ b/pandas/tseries/tests/test_resample.py
@@ -176,6 +176,54 @@ def test_resample_with_timedeltas(self):
assert_frame_equal(result, expected)
+ def test_resample_rounding(self):
+ # GH 8371
+ # odd results when rounding is needed
+
+ data = """date,time,value
+11-08-2014,00:00:01.093,1
+11-08-2014,00:00:02.159,1
+11-08-2014,00:00:02.667,1
+11-08-2014,00:00:03.175,1
+11-08-2014,00:00:07.058,1
+11-08-2014,00:00:07.362,1
+11-08-2014,00:00:08.324,1
+11-08-2014,00:00:08.830,1
+11-08-2014,00:00:08.982,1
+11-08-2014,00:00:09.815,1
+11-08-2014,00:00:10.540,1
+11-08-2014,00:00:11.061,1
+11-08-2014,00:00:11.617,1
+11-08-2014,00:00:13.607,1
+11-08-2014,00:00:14.535,1
+11-08-2014,00:00:15.525,1
+11-08-2014,00:00:17.960,1
+11-08-2014,00:00:20.674,1
+11-08-2014,00:00:21.191,1"""
+
+ from pandas.compat import StringIO
+ df = pd.read_csv(StringIO(data), parse_dates={'timestamp': ['date', 'time']}, index_col='timestamp')
+ df.index.name = None
+ result = df.resample('6s', how='sum')
+ expected = DataFrame({'value' : [4,9,4,2]},index=date_range('2014-11-08',freq='6s',periods=4))
+ assert_frame_equal(result,expected)
+
+ result = df.resample('7s', how='sum')
+ expected = DataFrame({'value' : [4,10,4,1]},index=date_range('2014-11-08',freq='7s',periods=4))
+ assert_frame_equal(result,expected)
+
+ result = df.resample('11s', how='sum')
+ expected = DataFrame({'value' : [11,8]},index=date_range('2014-11-08',freq='11s',periods=2))
+ assert_frame_equal(result,expected)
+
+ result = df.resample('13s', how='sum')
+ expected = DataFrame({'value' : [13,6]},index=date_range('2014-11-08',freq='13s',periods=2))
+ assert_frame_equal(result,expected)
+
+ result = df.resample('17s', how='sum')
+ expected = DataFrame({'value' : [16,3]},index=date_range('2014-11-08',freq='17s',periods=2))
+ assert_frame_equal(result,expected)
+
def test_resample_basic_from_daily(self):
# from daily
dti = DatetimeIndex(
| closes #8371
```
In [1]: data = """date,time,value
...: 11-08-2014,00:00:01.093,1
...: 11-08-2014,00:00:02.159,1
...: 11-08-2014,00:00:02.667,1
...: 11-08-2014,00:00:03.175,1
...: 11-08-2014,00:00:07.058,1
...: 11-08-2014,00:00:07.362,1
...: 11-08-2014,00:00:08.324,1
...: 11-08-2014,00:00:08.830,1
...: 11-08-2014,00:00:08.982,1
...: 11-08-2014,00:00:09.815,1
...: 11-08-2014,00:00:10.540,1
...: 11-08-2014,00:00:11.061,1
...: 11-08-2014,00:00:11.617,1
...: 11-08-2014,00:00:13.607,1
...: 11-08-2014,00:00:14.535,1
...: 11-08-2014,00:00:15.525,1
...: 11-08-2014,00:00:17.960,1
...: 11-08-2014,00:00:20.674,1
...: 11-08-2014,00:00:21.191,1"""
In [2]: df = pd.read_csv(StringIO(data), parse_dates={'timestamp': ['date', 'time']}, index_col='timestamp')
In [3]: df
Out[3]:
value
timestamp
2014-11-08 00:00:01.093000 1
2014-11-08 00:00:02.159000 1
2014-11-08 00:00:02.667000 1
2014-11-08 00:00:03.175000 1
2014-11-08 00:00:07.058000 1
2014-11-08 00:00:07.362000 1
2014-11-08 00:00:08.324000 1
2014-11-08 00:00:08.830000 1
2014-11-08 00:00:08.982000 1
2014-11-08 00:00:09.815000 1
2014-11-08 00:00:10.540000 1
2014-11-08 00:00:11.061000 1
2014-11-08 00:00:11.617000 1
2014-11-08 00:00:13.607000 1
2014-11-08 00:00:14.535000 1
2014-11-08 00:00:15.525000 1
2014-11-08 00:00:17.960000 1
2014-11-08 00:00:20.674000 1
2014-11-08 00:00:21.191000 1
In [4]: df.resample('6s', how='sum')
Out[4]:
value
timestamp
2014-11-08 00:00:00 4
2014-11-08 00:00:06 9
2014-11-08 00:00:12 4
2014-11-08 00:00:18 2
In [5]: df.resample('7s', how='sum')
Out[5]:
value
timestamp
2014-11-08 00:00:00 4
2014-11-08 00:00:07 10
2014-11-08 00:00:14 4
2014-11-08 00:00:21 1
In [6]: df.resample('11s', how='sum')
Out[6]:
value
timestamp
2014-11-08 00:00:00 11
2014-11-08 00:00:11 8
In [7]: df.resample('13s', how='sum')
Out[7]:
value
timestamp
2014-11-08 00:00:00 13
2014-11-08 00:00:13 6
In [8]: df.resample('17s', how='sum')
Out[8]:
value
timestamp
2014-11-08 00:00:00 16
2014-11-08 00:00:17 3
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/8372 | 2014-09-23T18:02:55Z | 2014-09-26T15:57:37Z | 2014-09-26T15:57:37Z | 2014-09-26T15:57:37Z |
BUG/COMPAT: set tz on DatetimeIndex on pickle reconstruction (GH8367) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index f49c919e80d50..cdf90e0a13cc0 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -506,7 +506,7 @@ Internal Refactoring
In 0.15.0 ``Index`` has internally been refactored to no longer sub-class ``ndarray``
but instead subclass ``PandasObject``, similarly to the rest of the pandas objects. This change allows very easy sub-classing and creation of new index types. This should be
-a transparent change with only very limited API implications (:issue:`5080`, :issue:`7439`, :issue:`7796`, :issue:`8024`)
+a transparent change with only very limited API implications (:issue:`5080`, :issue:`7439`, :issue:`7796`, :issue:`8024`, :issue:`8367`)
- you may need to unpickle pandas version < 0.15.0 pickles using ``pd.read_pickle`` rather than ``pickle.load``. See :ref:`pickle docs <io.pickle>`
- when plotting with a ``PeriodIndex``. The ``matplotlib`` internal axes will now be arrays of ``Period`` rather than a ``PeriodIndex``. (this is similar to how a ``DatetimeIndex`` passes arrays of ``datetimes`` now)
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 231a1a10d94f2..23f4cfd442a59 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -3323,8 +3323,8 @@ def __contains__(self, key):
def __reduce__(self):
"""Necessary for making this object picklable"""
- d = dict(levels = [lev.view(np.ndarray) for lev in self.levels],
- labels = [label.view(np.ndarray) for label in self.labels],
+ d = dict(levels = [lev for lev in self.levels],
+ labels = [label for label in self.labels],
sortorder = self.sortorder,
names = list(self.names))
return _new_Index, (self.__class__, d), None
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 295af483289e5..baa8f6411393e 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -1645,6 +1645,14 @@ def test_numeric_compat(self):
lambda : pd.date_range('2000-01-01', periods=3) * np.timedelta64(1, 'D').astype('m8[ns]') ]:
self.assertRaises(TypeError, f)
+ def test_roundtrip_pickle_with_tz(self):
+
+ # GH 8367
+ # round-trip of timezone
+ index=date_range('20130101',periods=3,tz='US/Eastern',name='foo')
+ unpickled = self.round_trip_pickle(index)
+ self.assertTrue(index.equals(unpickled))
+
class TestPeriodIndex(Base, tm.TestCase):
_holder = PeriodIndex
_multiprocess_can_split_ = True
@@ -2347,6 +2355,14 @@ def test_legacy_v2_unpickle(self):
assert_almost_equal(res, exp)
assert_almost_equal(exp, exp2)
+ def test_roundtrip_pickle_with_tz(self):
+
+ # GH 8367
+ # round-trip of timezone
+ index=MultiIndex.from_product([[1,2],['a','b'],date_range('20130101',periods=3,tz='US/Eastern')],names=['one','two','three'])
+ unpickled = self.round_trip_pickle(index)
+ self.assertTrue(index.equal_levels(unpickled))
+
def test_from_tuples_index_values(self):
result = MultiIndex.from_tuples(self.index)
self.assertTrue((result.values == self.index.values).all())
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 45e851afb49e0..8e39d3b3966e1 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -105,6 +105,17 @@ def _ensure_datetime64(other):
_midnight = time(0, 0)
+def _new_DatetimeIndex(cls, d):
+ """ This is called upon unpickling, rather than the default which doesn't have arguments
+ and breaks __new__ """
+
+ # simply set the tz
+ # data are already in UTC
+ tz = d.pop('tz',None)
+ result = cls.__new__(cls, **d)
+ result.tz = tz
+ return result
+
class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index):
"""
Immutable ndarray of datetime64 data, represented internally as int64, and
@@ -583,6 +594,15 @@ def _formatter_func(self):
formatter = _get_format_datetime64(is_dates_only=self._is_dates_only)
return lambda x: formatter(x, tz=self.tz)
+ def __reduce__(self):
+
+ # we use a special reudce here because we need
+ # to simply set the .tz (and not reinterpret it)
+
+ d = dict(data=self._data)
+ d.update(self._get_attributes_dict())
+ return _new_DatetimeIndex, (self.__class__, d), None
+
def __setstate__(self, state):
"""Necessary for making this object picklable"""
if isinstance(state, dict):
| closes #8367
| https://api.github.com/repos/pandas-dev/pandas/pulls/8370 | 2014-09-23T14:17:10Z | 2014-09-23T14:58:45Z | 2014-09-23T14:58:45Z | 2014-09-23T14:58:45Z |
DataFrame.dropna bug fix | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 4654ceee9896b..8c504d35a3a4f 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2552,7 +2552,11 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None,
agg_obj = self
if subset is not None:
ax = self._get_axis(agg_axis)
- agg_obj = self.take(ax.get_indexer_for(subset),axis=agg_axis)
+ indices = ax.get_indexer_for(subset)
+ if -1 in indices :
+ bad_keys = [col for (col,idx) in zip(subset,indices) if idx==-1]
+ raise KeyError(bad_keys)
+ agg_obj = self.take(indices,axis=agg_axis)
count = agg_obj.count(axis=agg_axis)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index b4b8e4263ec78..26d0b0cd940e8 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -7183,6 +7183,8 @@ def test_dropna_corner(self):
# bad input
self.assertRaises(ValueError, self.frame.dropna, how='foo')
self.assertRaises(TypeError, self.frame.dropna, how=None)
+ # non-existent column - 8303
+ self.assertRaises(KeyError, self.frame.dropna, subset=['A','X'])
def test_dropna_multiple_axes(self):
df = DataFrame([[1, np.nan, 2, 3],
| Bug fix for #8303. Now raise KeyError if any non-existent columns are passed in the subset argument.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8366 | 2014-09-23T01:44:39Z | 2014-09-25T00:05:35Z | null | 2014-09-25T00:38:15Z |
BUG: Bug in alignment with TimeOps and non-unique indexes (GH8363) | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index db55786ba0d1a..f49c919e80d50 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -867,7 +867,7 @@ Bug Fixes
- Bug in ``tslib.tz_convert`` and ``tslib.tz_convert_single`` may return different results (:issue:`7798`)
- Bug in ``DatetimeIndex.intersection`` of non-overlapping timestamps with tz raises ``IndexError`` (:issue:`7880`)
-
+- Bug in alignment with TimeOps and non-unique indexes (:issue:`8363`)
- Bug in ``GroupBy.filter()`` where fast path vs. slow path made the filter
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index f4192e5761d7a..c9f83bfe07116 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3112,9 +3112,13 @@ def _align_series(self, other, join='outer', axis=None, level=None,
raise ValueError('cannot align series to a series other than '
'axis 0')
- join_index, lidx, ridx = self.index.join(other.index, how=join,
- level=level,
- return_indexers=True)
+ # equal
+ if self.index.equals(other.index):
+ join_index, lidx, ridx = None, None, None
+ else:
+ join_index, lidx, ridx = self.index.join(other.index, how=join,
+ level=level,
+ return_indexers=True)
left_result = self._reindex_indexer(join_index, lidx, copy)
right_result = other._reindex_indexer(join_index, ridx, copy)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index b4b8e4263ec78..18de6ac35bf9c 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -3523,6 +3523,21 @@ def check(result, expected=None):
result = z.ix[['a', 'c', 'a']]
check(result,expected)
+
+ def test_column_dups_indexing2(self):
+
+ # GH 8363
+ # datetime ops with a non-unique index
+ df = DataFrame({'A' : np.arange(5), 'B' : np.arange(1,6)},index=[2,2,3,3,4])
+ result = df.B-df.A
+ expected = Series(1,index=[2,2,3,3,4])
+ assert_series_equal(result,expected)
+
+ df = DataFrame({'A' : date_range('20130101',periods=5), 'B' : date_range('20130101 09:00:00', periods=5)},index=[2,2,3,3,4])
+ result = df.B-df.A
+ expected = Series(Timedelta('9 hours'),index=[2,2,3,3,4])
+ assert_series_equal(result,expected)
+
def test_insert_benchmark(self):
# from the vb_suite/frame_methods/frame_insert_columns
N = 10
| closes #8363
| https://api.github.com/repos/pandas-dev/pandas/pulls/8364 | 2014-09-22T22:07:36Z | 2014-09-23T01:05:32Z | 2014-09-23T01:05:32Z | 2014-09-23T01:05:32Z |
BUG: OLS with clustering and nw_lags does not error | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index c66cda58fa8a0..672b58ccb75ad 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -940,3 +940,6 @@ Bug Fixes
- Bug where ``col_space`` was ignored in ``DataFrame.to_string()`` when ``header=False`` (:issue:`8230`).
- Bug in DataFrame terminal display: Setting max_column/max_rows to zero did not trigger auto-resizing of dfs to fit terminal width/height (:issue:`7180`).
+- Bug in OLS where running with "cluster" and "nw_lags" parameters did not work correctly, but also did not throw an error
+ (:issue:`5884', :issue:`8360`).
+
diff --git a/pandas/stats/interface.py b/pandas/stats/interface.py
index 6d7bf329b4bee..96b2b3e32be0d 100644
--- a/pandas/stats/interface.py
+++ b/pandas/stats/interface.py
@@ -83,6 +83,14 @@ def ols(**kwargs):
The appropriate OLS object, which allows you to obtain betas and various
statistics, such as std err, t-stat, etc.
"""
+
+ if (kwargs.get('cluster') is not None and
+ kwargs.get('nw_lags') is not None):
+ raise ValueError(
+ 'Pandas OLS does not work with Newey-West correction '
+ 'and clustering.')
+
+
pool = kwargs.get('pool')
if 'pool' in kwargs:
del kwargs['pool']
diff --git a/pandas/stats/tests/test_ols.py b/pandas/stats/tests/test_ols.py
index 5a34048fd8c8c..5c8d47ec2a82a 100644
--- a/pandas/stats/tests/test_ols.py
+++ b/pandas/stats/tests/test_ols.py
@@ -682,13 +682,15 @@ def testRollingWithTimeCluster(self):
cluster='time')
def testRollingWithNeweyWestAndEntityCluster(self):
- self.checkMovingOLS(self.panel_x, self.panel_y,
- nw_lags=1, cluster='entity')
+ self.assertRaises(ValueError, self.checkMovingOLS,
+ self.panel_x, self.panel_y,
+ nw_lags=1, cluster='entity')
def testRollingWithNeweyWestAndTimeEffectsAndEntityCluster(self):
- self.checkMovingOLS(self.panel_x, self.panel_y,
- nw_lags=1, cluster='entity',
- time_effects=True)
+ self.assertRaises(ValueError,
+ self.checkMovingOLS, self.panel_x, self.panel_y,
+ nw_lags=1, cluster='entity',
+ time_effects=True)
def testExpanding(self):
self.checkMovingOLS(
| Added statement to raise ValueError when OLS is run with clustering and
Newey-West adjustments. Closes #5884. This is a re-attempt at
GH8170.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8360 | 2014-09-22T19:03:23Z | 2014-09-23T14:24:16Z | null | 2014-09-23T14:38:37Z |
Changed round_trip converter to Python converter instead of strtod | diff --git a/pandas/src/parser/tokenizer.c b/pandas/src/parser/tokenizer.c
index f817b202632e5..9a7303b6874db 100644
--- a/pandas/src/parser/tokenizer.c
+++ b/pandas/src/parser/tokenizer.c
@@ -2292,7 +2292,11 @@ double precise_xstrtod(const char *str, char **endptr, char decimal,
double round_trip(const char *p, char **q, char decimal, char sci,
char tsep, int skip_trailing)
{
+#if PY_VERSION_HEX >= 0x02070000
+ return PyOS_string_to_double(p, q, 0);
+#else
return strtod(p, q);
+#endif
}
/*
diff --git a/pandas/src/parser/tokenizer.h b/pandas/src/parser/tokenizer.h
index 1ad7106ef123f..0947315fbe6b7 100644
--- a/pandas/src/parser/tokenizer.h
+++ b/pandas/src/parser/tokenizer.h
@@ -12,6 +12,7 @@ See LICENSE for the license
#ifndef _PARSER_COMMON_H_
#define _PARSER_COMMON_H_
+#include "Python.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
| As @mdickinson noted in #8044.
| https://api.github.com/repos/pandas-dev/pandas/pulls/8357 | 2014-09-22T16:08:17Z | 2014-09-27T01:48:08Z | 2014-09-27T01:48:08Z | 2014-09-28T16:24:39Z |
BUG: Work-around openpyxl-2.1.0 NumberFormat removal | diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index 84f04188b7906..dcecbedd87dcf 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -71,7 +71,7 @@ def read_excel(io, sheetname=0, **kwds):
Parameters
----------
- io : string, file-like object, or xlrd workbook.
+ io : string, file-like object, or xlrd workbook.
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/workbook.xlsx
@@ -166,7 +166,7 @@ def __init__(self, io, **kwds):
self.book = io
elif not isinstance(io, xlrd.Book) and hasattr(io, "read"):
# N.B. xlrd.Book has a read attribute too
- data = io.read()
+ data = io.read()
self.book = xlrd.open_workbook(file_contents=data)
else:
raise ValueError('Must explicitly set engine if not passing in'
@@ -1029,21 +1029,24 @@ def _convert_to_alignment(cls, alignment_dict):
@classmethod
def _convert_to_number_format(cls, number_format_dict):
"""
- Convert ``number_format_dict`` to an openpyxl v2 NumberFormat object.
+ Convert ``number_format_dict`` to an openpyxl v2.1.0 number format
+ initializer.
Parameters
----------
number_format_dict : dict
A dict with zero or more of the following keys.
- 'format_code'
+ 'format_code' : str
Returns
-------
- number_format : openpyxl.styles.NumberFormat
+ number_format : str
"""
-
- from openpyxl.styles import NumberFormat
-
- return NumberFormat(**number_format_dict)
-
+ try:
+ # >= 2.0.0 < 2.1.0
+ from openpyxl.styles import NumberFormat
+ return NumberFormat(**number_format_dict)
+ except:
+ # >= 2.1.0
+ return number_format_dict['format_code']
@classmethod
def _convert_to_protection(cls, protection_dict):
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 17407e3a864e2..662f12da8c4d0 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -1198,6 +1198,7 @@ def test_to_excel_styleconverter(self):
if not openpyxl_compat.is_compat(major_ver=2):
raise nose.SkipTest('incompatiable openpyxl version')
+ import openpyxl
from openpyxl import styles
hstyle = {
@@ -1238,7 +1239,14 @@ def test_to_excel_styleconverter(self):
alignment = styles.Alignment(horizontal='center', vertical='top')
fill_color = styles.Color(rgb='006666FF', tint=0.3)
fill = styles.PatternFill(patternType='solid', fgColor=fill_color)
- number_format = styles.NumberFormat(format_code='0.00')
+
+ # ahh openpyxl API changes
+ ver = openpyxl.__version__
+ if ver >= LooseVersion('2.0.0') and ver < LooseVersion('2.1.0'):
+ number_format = styles.NumberFormat(format_code='0.00')
+ else:
+ number_format = '0.00' # XXX: Only works with openpyxl-2.1.0
+
protection = styles.Protection(locked=True, hidden=False)
kw = _Openpyxl2Writer._convert_to_style_kwargs(hstyle)
| xref #8342
compat for openpyxl: 2.0.0 thru 2.1.0, but a bit hacky
| https://api.github.com/repos/pandas-dev/pandas/pulls/8356 | 2014-09-22T15:54:57Z | 2014-09-22T16:39:26Z | 2014-09-22T16:39:26Z | 2014-09-22T16:39:26Z |
Test margins with dictionary aggfunc | diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py
index cf28c2400524c..42773776afa09 100644
--- a/pandas/tools/tests/test_pivot.py
+++ b/pandas/tools/tests/test_pivot.py
@@ -266,6 +266,25 @@ def _check_output(res, col, index=['A', 'B'], columns=['C']):
gmarg = table[item]['All', '']
self.assertEqual(gmarg, self.data[item].mean())
+ # test margins with dictionary aggfunc
+
+ self.data=pd.DataFrame([{'JOB':'Worker','NAME':'Bob' ,'YEAR':2013,'MONTH':12,'DAYS': 3,'SALARY': 17},
+ {'JOB':'Employ','NAME':'Mary','YEAR':2013,'MONTH':12,'DAYS': 5,'SALARY': 23},
+ {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':10,'SALARY':100},
+ {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':11,'SALARY':110},
+ {'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 1,'DAYS':15,'SALARY':200},
+ {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 2,'DAYS': 8,'SALARY': 80},
+ {'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 2,'DAYS': 5,'SALARY':190} ])
+
+ self.data=self.data.set_index(['JOB','NAME','YEAR','MONTH'],drop=False,append=False)
+
+ table=self.data.pivot_table(index=['JOB','NAME'],
+ columns=['YEAR','MONTH'],
+ values=['DAYS','SALARY'],
+ aggfunc={'DAYS':'mean','SALARY':'sum'},
+ margins=True)
+
+
def test_pivot_integer_columns(self):
# caused by upstream bug in unstack
| https://api.github.com/repos/pandas-dev/pandas/pulls/8355 | 2014-09-22T15:33:12Z | 2014-09-23T07:50:42Z | null | 2014-09-23T12:26:37Z | |
Bug on pivot_table with margins and dict aggfunc | diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt
index fcf928a975c2b..4e8b2ba7c9777 100644
--- a/doc/source/v0.15.0.txt
+++ b/doc/source/v0.15.0.txt
@@ -854,7 +854,7 @@ Performance
Bug Fixes
~~~~~~~~~
-
+- Bug in pivot_table, "key error" using margins and dict aggfunc (:issue:`8349`)
- Bug in ``read_csv`` where ``squeeze=True`` would return a view (:issue:`8217`)
- Bug in checking of table name in ``read_sql`` in certain cases (:issue:`7826`).
- Bug in ``DataFrame.groupby`` where ``Grouper`` does not recognize level when frequency is specified (:issue:`7885`)
diff --git a/pandas/tools/pivot.py b/pandas/tools/pivot.py
index 61150f0aeacd0..ef477582b82f2 100644
--- a/pandas/tools/pivot.py
+++ b/pandas/tools/pivot.py
@@ -207,6 +207,11 @@ def _compute_grand_margin(data, values, aggfunc):
try:
if isinstance(aggfunc, compat.string_types):
grand_margin[k] = getattr(v, aggfunc)()
+ elif isinstance(aggfunc, dict):
+ if isinstance(aggfunc[k], compat.string_types):
+ grand_margin[k] = getattr(v, aggfunc[k])()
+ else:
+ grand_margin[k] = aggfunc[k](v)
else:
grand_margin[k] = aggfunc(v)
except TypeError:
diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py
index cf28c2400524c..23350b203ee50 100644
--- a/pandas/tools/tests/test_pivot.py
+++ b/pandas/tools/tests/test_pivot.py
@@ -266,6 +266,34 @@ def _check_output(res, col, index=['A', 'B'], columns=['C']):
gmarg = table[item]['All', '']
self.assertEqual(gmarg, self.data[item].mean())
+ # issue number #8349: pivot_table with margins and dictionary aggfunc
+
+ df=DataFrame([ {'JOB':'Worker','NAME':'Bob' ,'YEAR':2013,'MONTH':12,'DAYS': 3,'SALARY': 17},
+ {'JOB':'Employ','NAME':'Mary','YEAR':2013,'MONTH':12,'DAYS': 5,'SALARY': 23},
+ {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':10,'SALARY':100},
+ {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':11,'SALARY':110},
+ {'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 1,'DAYS':15,'SALARY':200},
+ {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 2,'DAYS': 8,'SALARY': 80},
+ {'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 2,'DAYS': 5,'SALARY':190} ])
+
+ df=df.set_index(['JOB','NAME','YEAR','MONTH'],drop=False,append=False)
+
+ rs=df.pivot_table( index=['JOB','NAME'],
+ columns=['YEAR','MONTH'],
+ values=['DAYS','SALARY'],
+ aggfunc={'DAYS':'mean','SALARY':'sum'},
+ margins=True)
+
+ ex=df.pivot_table(index=['JOB','NAME'],columns=['YEAR','MONTH'],values=['DAYS'],aggfunc='mean',margins=True)
+
+ tm.assert_frame_equal(rs['DAYS'], ex['DAYS'])
+
+ ex=df.pivot_table(index=['JOB','NAME'],columns=['YEAR','MONTH'],values=['SALARY'],aggfunc='sum',margins=True)
+
+ tm.assert_frame_equal(rs['SALARY'], ex['SALARY'])
+
+
+
def test_pivot_integer_columns(self):
# caused by upstream bug in unstack
| closes #8349
bug on pandas 0.14.1 pivot_table using dictionary aggfunc and margins.
Test code:
<pre>
<code>
df=pandas.DataFrame([
{'JOB':'Worker','NAME':'Bob' ,'YEAR':2013,'MONTH':12,'DAYS': 3,'SALARY': 17},
{'JOB':'Employ','NAME':'Mary','YEAR':2013,'MONTH':12,'DAYS': 5,'SALARY': 23},
{'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':10,'SALARY':100},
{'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':11,'SALARY':110},
{'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 1,'DAYS':15,'SALARY':200},
{'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 2,'DAYS': 8,'SALARY': 80},
{'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 2,'DAYS': 5,'SALARY':190} ])
df=df.set_index(['JOB','NAME','YEAR','MONTH'],drop=False,append=False)
df=df.pivot_table(index=['JOB','NAME'],
columns=['YEAR','MONTH'],
values=['DAYS','SALARY'],
aggfunc={'DAYS':'mean','SALARY':'sum'})
</code>
</pre>
All works fine but raise error using margins:
<pre>
<code>
df=df.pivot_table(index=['JOB','NAME'],
columns=['YEAR','MONTH'],
values=['DAYS','SALARY'],
aggfunc={'DAYS':'mean','SALARY':'sum'},
margins=True)
</code>
</pre>
df=df.pivot_table(index=['JOB','NAME'],columns=['YEAR','MONTH'],values=['DAYS','SALARY'],aggfunc={'DAYS':'mean','SALARY':'sum'},margins=True)
File "/usr/local/lib/python2.7/site-packages/pandas-0.14.1-py2.7-linux-x86_64.egg/pandas/util/decorators.py", line 60, in wrapper
return func(_args, *_kwargs)
File "/usr/local/lib/python2.7/site-packages/pandas-0.14.1-py2.7-linux-x86_64.egg/pandas/util/decorators.py", line 60, in wrapper
return func(_args, *_kwargs)
File "/usr/local/lib/python2.7/site-packages/pandas-0.14.1-py2.7-linux-x86_64.egg/pandas/tools/pivot.py", line 147, in pivot_table
cols=columns, aggfunc=aggfunc)
File "/usr/local/lib/python2.7/site-packages/pandas-0.14.1-py2.7-linux-x86_64.egg/pandas/tools/pivot.py", line 191, in _add_margins
row_margin[k] = grand_margin[k[0]]
KeyError: 'SALARY'
| https://api.github.com/repos/pandas-dev/pandas/pulls/8354 | 2014-09-22T15:19:37Z | 2014-09-30T16:05:15Z | null | 2014-09-30T16:05:42Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.