after_merge
stringlengths
28
79.6k
before_merge
stringlengths
20
79.6k
url
stringlengths
38
71
full_traceback
stringlengths
43
922k
traceback_type
stringclasses
555 values
def _interleave(self, items): """ Return ndarray from blocks with specified item order Items must be contained in the blocks """ dtype = _interleaved_dtype(self.blocks) items = _ensure_index(items) result = np.empty(self.shape, dtype=dtype) itemmask = np.zeros(len(items), dtype=bool) # By construction, all of the item should be covered by one of the # blocks if items.is_unique: for block in self.blocks: indexer = items.get_indexer(block.items) assert (indexer != -1).all() result[indexer] = block.get_values(dtype) itemmask[indexer] = 1 else: for block in self.blocks: mask = items.isin(block.items) indexer = mask.nonzero()[0] assert len(indexer) == len(block.items) result[indexer] = block.get_values(dtype) itemmask[indexer] = 1 assert itemmask.all() return result
def _interleave(self, items): """ Return ndarray from blocks with specified item order Items must be contained in the blocks """ dtype = _interleaved_dtype(self.blocks) items = _ensure_index(items) result = np.empty(self.shape, dtype=dtype) itemmask = np.zeros(len(items), dtype=bool) # By construction, all of the item should be covered by one of the # blocks for block in self.blocks: indexer = items.get_indexer(block.items) assert (indexer != -1).all() result[indexer] = block.get_values(dtype) itemmask[indexer] = 1 assert itemmask.all() return result
https://github.com/pandas-dev/pandas/issues/2236
import pandas as pd def runNow(): #identify sheet source = 'C:\Users\jlalonde\Desktop\startup_geno\startupgenome_w_id_xl_20121109.xlsx' xls_file = pd.ExcelFile(source) sd = xls_file.parse('Sheet1') source_u = sd.drop_duplicates(cols = 'id_company', take_last=False) source_r = source_u[['id_company','id_good','description', 'website','keyword', 'company_name','founded_month', 'founded_year', 'description']] source_i = source_r.reindex() #hail mary tup_r = [tuple(x) for x in source_i.values] Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> sg_sql_2.runNow() File "sg_sql_2.py", line 31, in runNow tup_r = [tuple(x) for x in source_r.values] File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1443, in as_matrix return self._data.as_matrix(columns).T File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 723, in as_matrix mat = self._interleave(self.items) File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 743, in _interleave indexer = items.get_indexer(block.items) File "C:\Python27\lib\site-packages\pandas\core\index.py", line 748, in get_indexer raise Exception('Reindexing only valid with uniquely valued Index ' Exception: Reindexing only valid with uniquely valued Index objects
Exception
def _isnull_ndarraylike(obj): from pandas import Series values = np.asarray(obj) if values.dtype.kind in ("O", "S", "U"): # Working around NumPy ticket 1542 shape = values.shape if values.dtype.kind in ("S", "U"): result = np.zeros(values.shape, dtype=bool) else: result = np.empty(shape, dtype=bool) vec = lib.isnullobj(values.ravel()) result[:] = vec.reshape(shape) if isinstance(obj, Series): result = Series(result, index=obj.index, copy=False) elif values.dtype == np.dtype("M8[ns]"): # this is the NaT pattern result = values.view("i8") == lib.iNaT elif issubclass(values.dtype.type, np.timedelta64): result = -np.isfinite(values.view("i8")) else: result = -np.isfinite(obj) return result
def _isnull_ndarraylike(obj): from pandas import Series values = np.asarray(obj) if values.dtype.kind in ("O", "S", "U"): # Working around NumPy ticket 1542 shape = values.shape if values.dtype.kind in ("S", "U"): result = np.zeros(values.shape, dtype=bool) else: result = np.empty(shape, dtype=bool) vec = lib.isnullobj(values.ravel()) result[:] = vec.reshape(shape) if isinstance(obj, Series): result = Series(result, index=obj.index, copy=False) elif values.dtype == np.dtype("M8[ns]"): # this is the NaT pattern result = values.view("i8") == lib.iNaT else: result = -np.isfinite(obj) return result
https://github.com/pandas-dev/pandas/issues/2146
import pandas as pd import numpy as np print pd.Series(np.array([1100, 20], dtype='timedelta64[s]')) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 911, in __str__ return repr(self) File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 847, in __repr__ name=True) File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 908, in _get_repr return formatter.to_string() File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 126, in to_string fmt_values = self._get_formatted_values() File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 117, in _get_formatted_values na_rep=self.na_rep) File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 691, in format_array return fmt_obj.get_result() File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 814, in get_result fmt_values = [formatter(x) for x in self.values] File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 812, in <lambda> formatter = lambda x: '% d' % x TypeError: %d format: a number is required, not numpy.timedelta64
TypeError
def is_integer_dtype(arr_or_dtype): if isinstance(arr_or_dtype, np.dtype): tipo = arr_or_dtype.type else: tipo = arr_or_dtype.dtype.type return issubclass(tipo, np.integer) and not ( issubclass(tipo, np.datetime64) or issubclass(tipo, np.timedelta64) )
def is_integer_dtype(arr_or_dtype): if isinstance(arr_or_dtype, np.dtype): tipo = arr_or_dtype.type else: tipo = arr_or_dtype.dtype.type return issubclass(tipo, np.integer) and not issubclass(tipo, np.datetime64)
https://github.com/pandas-dev/pandas/issues/2146
import pandas as pd import numpy as np print pd.Series(np.array([1100, 20], dtype='timedelta64[s]')) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 911, in __str__ return repr(self) File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 847, in __repr__ name=True) File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 908, in _get_repr return formatter.to_string() File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 126, in to_string fmt_values = self._get_formatted_values() File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 117, in _get_formatted_values na_rep=self.na_rep) File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 691, in format_array return fmt_obj.get_result() File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 814, in get_result fmt_values = [formatter(x) for x in self.values] File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 812, in <lambda> formatter = lambda x: '% d' % x TypeError: %d format: a number is required, not numpy.timedelta64
TypeError
def __new__( cls, data=None, freq=None, start=None, end=None, periods=None, copy=False, name=None, tz=None, verify_integrity=True, normalize=False, **kwds, ): dayfirst = kwds.pop("dayfirst", None) yearfirst = kwds.pop("yearfirst", None) warn = False if "offset" in kwds and kwds["offset"]: freq = kwds["offset"] warn = True freq_infer = False if not isinstance(freq, DateOffset): if freq != "infer": freq = to_offset(freq) else: freq_infer = True freq = None if warn: import warnings warnings.warn( "parameter 'offset' is deprecated, please use 'freq' instead", FutureWarning ) offset = freq if periods is not None: if com.is_float(periods): periods = int(periods) elif not com.is_integer(periods): raise ValueError("Periods must be a number, got %s" % str(periods)) if data is None and offset is None: raise ValueError("Must provide freq argument if no data is supplied") if data is None: return cls._generate( start, end, periods, name, offset, tz=tz, normalize=normalize ) if not isinstance(data, np.ndarray): if np.isscalar(data): raise ValueError( "DatetimeIndex() must be called with a " "collection of some kind, %s was passed" % repr(data) ) # other iterable of some kind if not isinstance(data, (list, tuple)): data = list(data) data = np.asarray(data, dtype="O") # try a few ways to make it datetime64 if lib.is_string_array(data): data = _str_to_dt_array( data, offset, dayfirst=dayfirst, yearfirst=yearfirst ) else: data = tools.to_datetime(data) data.offset = offset if isinstance(data, DatetimeIndex): if name is not None: data.name = name return data if issubclass(data.dtype.type, basestring): subarr = _str_to_dt_array(data, offset, dayfirst=dayfirst, yearfirst=yearfirst) elif issubclass(data.dtype.type, np.datetime64): if isinstance(data, DatetimeIndex): if tz is None: tz = data.tz subarr = data.values if offset is None: offset = data.offset verify_integrity = False else: if data.dtype != _NS_DTYPE: subarr = lib.cast_to_nanoseconds(data) else: subarr = data elif data.dtype == _INT64_DTYPE: if isinstance(data, Int64Index): raise TypeError("cannot convert Int64Index->DatetimeIndex") if copy: subarr = np.asarray(data, dtype=_NS_DTYPE) else: subarr = data.view(_NS_DTYPE) else: try: subarr = tools.to_datetime(data) except ValueError: # tz aware subarr = tools.to_datetime(data, utc=True) if not np.issubdtype(subarr.dtype, np.datetime64): raise TypeError("Unable to convert %s to datetime dtype" % str(data)) if isinstance(subarr, DatetimeIndex): if tz is None: tz = subarr.tz else: if tz is not None: tz = tools._maybe_get_tz(tz) # Convert local to UTC ints = subarr.view("i8") subarr = lib.tz_localize_to_utc(ints, tz) subarr = subarr.view(_NS_DTYPE) subarr = subarr.view(cls) subarr.name = name subarr.offset = offset subarr.tz = tz if verify_integrity and len(subarr) > 0: if offset is not None and not freq_infer: inferred = subarr.inferred_freq if inferred != offset.freqstr: raise ValueError("Dates do not conform to passed frequency") if freq_infer: inferred = subarr.inferred_freq if inferred: subarr.offset = to_offset(inferred) return subarr
def __new__( cls, data=None, freq=None, start=None, end=None, periods=None, copy=False, name=None, tz=None, verify_integrity=True, normalize=False, **kwds, ): dayfirst = kwds.pop("dayfirst", None) yearfirst = kwds.pop("yearfirst", None) warn = False if "offset" in kwds and kwds["offset"]: freq = kwds["offset"] warn = True freq_infer = False if not isinstance(freq, DateOffset): if freq != "infer": freq = to_offset(freq) else: freq_infer = True freq = None if warn: import warnings warnings.warn( "parameter 'offset' is deprecated, please use 'freq' instead", FutureWarning ) offset = freq if periods is not None: if com.is_float(periods): periods = int(periods) elif not com.is_integer(periods): raise ValueError("Periods must be a number, got %s" % str(periods)) if data is None and offset is None: raise ValueError("Must provide freq argument if no data is supplied") if data is None: return cls._generate( start, end, periods, name, offset, tz=tz, normalize=normalize ) if not isinstance(data, np.ndarray): if np.isscalar(data): raise ValueError( "DatetimeIndex() must be called with a " "collection of some kind, %s was passed" % repr(data) ) # other iterable of some kind if not isinstance(data, (list, tuple)): data = list(data) data = np.asarray(data, dtype="O") # try a few ways to make it datetime64 if lib.is_string_array(data): data = _str_to_dt_array( data, offset, dayfirst=dayfirst, yearfirst=yearfirst ) else: data = tools.to_datetime(data) data.offset = offset if isinstance(data, DatetimeIndex): if name is not None: data.name = name return data if issubclass(data.dtype.type, basestring): subarr = _str_to_dt_array(data, offset, dayfirst=dayfirst, yearfirst=yearfirst) elif issubclass(data.dtype.type, np.datetime64): if isinstance(data, DatetimeIndex): if tz is None: tz = data.tz subarr = data.values if offset is None: offset = data.offset verify_integrity = False else: if data.dtype != _NS_DTYPE: subarr = lib.cast_to_nanoseconds(data) else: subarr = data elif data.dtype == _INT64_DTYPE: if copy: subarr = np.asarray(data, dtype=_NS_DTYPE) else: subarr = data.view(_NS_DTYPE) else: try: subarr = tools.to_datetime(data) except ValueError: # tz aware subarr = tools.to_datetime(data, utc=True) if not np.issubdtype(subarr.dtype, np.datetime64): raise TypeError("Unable to convert %s to datetime dtype" % str(data)) if isinstance(subarr, DatetimeIndex): if tz is None: tz = subarr.tz else: if tz is not None: tz = tools._maybe_get_tz(tz) # Convert local to UTC ints = subarr.view("i8") subarr = lib.tz_localize_to_utc(ints, tz) subarr = subarr.view(_NS_DTYPE) subarr = subarr.view(cls) subarr.name = name subarr.offset = offset subarr.tz = tz if verify_integrity and len(subarr) > 0: if offset is not None and not freq_infer: inferred = subarr.inferred_freq if inferred != offset.freqstr: raise ValueError("Dates do not conform to passed frequency") if freq_infer: inferred = subarr.inferred_freq if inferred: subarr.offset = to_offset(inferred) return subarr
https://github.com/pandas-dev/pandas/issues/1866
building [html]: targets for 22 source files that are out of date updating environment: 218 added, 0 changed, 0 removed --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-767-cc6f0e841b62> in <module>() 1 df = read_csv('tmp.csv', header=None, parse_dates=date_spec, ----> 2 date_parser=conv.parse_date_time) /home/wesm/code/pandas/pandas/io/parsers.pyc in read_csv(filepath_or_buffer, sep, dialect, header, index_col, names, skiprows, na_values, keep_default_na, thousands, comment, parse_dates, keep_date_col, dayfirst, date_parser, nrows, iterator, chunksize, skip_footer, converters, verbose, delimiter, encoding, squeeze) 239 kwds['delimiter'] = sep 240 --> 241 return _read(TextParser, filepath_or_buffer, kwds) 242 243 @Appender(_read_table_doc) /home/wesm/code/pandas/pandas/io/parsers.pyc in _read(cls, filepath_or_buffer, kwds) 192 return parser 193 --> 194 return parser.get_chunk() 195 196 @Appender(_read_csv_doc) /home/wesm/code/pandas/pandas/io/parsers.pyc in get_chunk(self, rows) 812 columns = list(self.columns) 813 if self.parse_dates is not None: --> 814 data, columns = self._process_date_conversion(data) 815 816 df = DataFrame(data=data, columns=columns, index=index) /home/wesm/code/pandas/pandas/io/parsers.pyc in _process_date_conversion(self, data_dict) 989 990 _, col, old_names = _try_convert_dates( --> 991 self._conv_date, colspec, data_dict, self.orig_columns) 992 993 new_data[new_name] = col /home/wesm/code/pandas/pandas/io/parsers.pyc in _try_convert_dates(parser, colspec, data_dict, columns) 1120 to_parse = [data_dict[c] for c in colspec if c in data_dict] 1121 try: -> 1122 new_col = parser(*to_parse) 1123 except DateConversionError: 1124 new_col = parser(_concat_date_cols(to_parse)) /home/wesm/code/pandas/pandas/io/parsers.pyc in _conv_date(self, *date_cols) 951 return lib.try_parse_dates(_concat_date_cols(date_cols), 952 parser=self.date_parser, --> 953 dayfirst=self.dayfirst) 954 955 def _process_date_conversion(self, data_dict): /home/wesm/code/pandas/pandas/lib.so in pandas.lib.try_parse_dates (pandas/src/tseries.c:98928)() /home/wesm/code/pandas/pandas/lib.so in pandas.lib.try_parse_dates (pandas/src/tseries.c:98870)() TypeError: parse_date_time() takes exactly 2 arguments (1 given) reading sources... [100%] whatsnew /home/wesm/code/pandas/doc/source/faq.rst:74: ERROR: Unknown interpreted text role "issue". source/v0.8.0.txt:151: WARNING: Inline literal start-st
TypeError
def take_2d_multi(arr, row_idx, col_idx, fill_value=np.nan, out=None): dtype_str = arr.dtype.name out_shape = len(row_idx), len(col_idx) if dtype_str in ("int32", "int64", "bool"): row_mask = row_idx == -1 col_mask = col_idx == -1 needs_masking = row_mask.any() or col_mask.any() if needs_masking: return take_2d_multi( _maybe_upcast(arr), row_idx, col_idx, fill_value=fill_value, out=out ) else: if out is None: out = np.empty(out_shape, dtype=arr.dtype) take_f = _get_take2d_function(dtype_str, axis="multi") take_f( arr, _ensure_int64(row_idx), _ensure_int64(col_idx), out=out, fill_value=fill_value, ) return out elif dtype_str in ("float64", "object", "datetime64[ns]"): if out is None: out = np.empty(out_shape, dtype=arr.dtype) take_f = _get_take2d_function(dtype_str, axis="multi") take_f( arr, _ensure_int64(row_idx), _ensure_int64(col_idx), out=out, fill_value=fill_value, ) return out else: if out is not None: raise ValueError("Cannot pass out in this case") return take_2d( take_2d(arr, row_idx, axis=0, fill_value=fill_value), col_idx, axis=1, fill_value=fill_value, )
def take_2d_multi(arr, row_idx, col_idx, fill_value=np.nan): dtype_str = arr.dtype.name out_shape = len(row_idx), len(col_idx) if dtype_str in ("int32", "int64", "bool"): row_mask = row_idx == -1 col_mask = col_idx == -1 needs_masking = row_mask.any() or col_mask.any() if needs_masking: return take_2d_multi( _maybe_upcast(arr), row_idx, col_idx, fill_value=fill_value ) else: out = np.empty(out_shape, dtype=arr.dtype) take_f = _get_take2d_function(dtype_str, axis="multi") take_f( arr, _ensure_int64(row_idx), _ensure_int64(col_idx), out=out, fill_value=fill_value, ) return out elif dtype_str in ("float64", "object", "datetime64[ns]"): out = np.empty(out_shape, dtype=arr.dtype) take_f = _get_take2d_function(dtype_str, axis="multi") take_f( arr, _ensure_int64(row_idx), _ensure_int64(col_idx), out=out, fill_value=fill_value, ) return out else: return take_2d( take_2d(arr, row_idx, axis=0, fill_value=fill_value), col_idx, axis=1, fill_value=fill_value, )
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def resample( self, rule, how=None, axis=0, fill_method=None, closed="right", label="right", convention=None, kind=None, loffset=None, limit=None, base=0, ): """ Convenience method for frequency conversion and resampling of regular time-series data. Parameters ---------- rule : the offset string or object representing target conversion how : string, method for down- or re-sampling, default to 'mean' for downsampling fill_method : string, fill_method for upsampling, default None axis : int, optional, default 0 closed : {'right', 'left'}, default 'right' Which side of bin interval is closed label : {'right', 'left'}, default 'right' Which bin edge label to label bucket with convention : {'start', 'end', 's', 'e'} loffset : timedelta Adjust the resampled time labels base : int, default 0 For frequencies that evenly subdivide 1 day, the "origin" of the aggregated intervals. For example, for '5min' frequency, base could range from 0 through 4. Defaults to 0 """ from pandas.tseries.resample import TimeGrouper sampler = TimeGrouper( rule, label=label, closed=closed, how=how, axis=axis, kind=kind, loffset=loffset, fill_method=fill_method, convention=convention, limit=limit, base=base, ) return sampler.resample(self)
def resample( self, rule, how="mean", axis=0, fill_method=None, closed="right", label="right", convention=None, kind=None, loffset=None, limit=None, base=0, ): """ Convenience method for frequency conversion and resampling of regular time-series data. Parameters ---------- rule : the offset string or object representing target conversion how : string, method for down- or re-sampling, default 'mean' fill_method : string, fill_method for upsampling, default None axis : int, optional, default 0 closed : {'right', 'left'}, default 'right' Which side of bin interval is closed label : {'right', 'left'}, default 'right' Which bin edge label to label bucket with convention : {'start', 'end', 's', 'e'} loffset : timedelta Adjust the resampled time labels base : int, default 0 For frequencies that evenly subdivide 1 day, the "origin" of the aggregated intervals. For example, for '5min' frequency, base could range from 0 through 4. Defaults to 0 """ from pandas.tseries.resample import TimeGrouper sampler = TimeGrouper( rule, label=label, closed=closed, how=how, axis=axis, kind=kind, loffset=loffset, fill_method=fill_method, convention=convention, limit=limit, base=base, ) return sampler.resample(self)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _nanmin(values, axis=None, skipna=True): mask = isnull(values) if skipna and not issubclass(values.dtype.type, (np.integer, np.datetime64)): values = values.copy() np.putmask(values, mask, np.inf) # numpy 1.6.1 workaround in Python 3.x if values.dtype == np.object_ and sys.version_info[0] >= 3: # pragma: no cover import __builtin__ if values.ndim > 1: apply_ax = axis if axis is not None else 0 result = np.apply_along_axis(__builtin__.min, apply_ax, values) else: result = __builtin__.min(values) else: if (axis is not None and values.shape[axis] == 0) or values.size == 0: result = values.sum(axis) result.fill(np.nan) else: result = values.min(axis) return _maybe_null_out(result, axis, mask)
def _nanmin(values, axis=None, skipna=True): mask = isnull(values) if skipna and not issubclass(values.dtype.type, (np.integer, np.datetime64)): values = values.copy() np.putmask(values, mask, np.inf) # numpy 1.6.1 workaround in Python 3.x if values.dtype == np.object_ and sys.version_info[0] >= 3: # pragma: no cover import __builtin__ if values.ndim > 1: apply_ax = axis if axis is not None else 0 result = np.apply_along_axis(__builtin__.min, apply_ax, values) else: result = __builtin__.min(values) else: result = values.min(axis) return _maybe_null_out(result, axis, mask)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _nanmax(values, axis=None, skipna=True): mask = isnull(values) if skipna and not issubclass(values.dtype.type, (np.integer, np.datetime64)): values = values.copy() np.putmask(values, mask, -np.inf) # numpy 1.6.1 workaround in Python 3.x if values.dtype == np.object_ and sys.version_info[0] >= 3: # pragma: no cover import __builtin__ if values.ndim > 1: apply_ax = axis if axis is not None else 0 result = np.apply_along_axis(__builtin__.max, apply_ax, values) else: result = __builtin__.max(values) else: if (axis is not None and values.shape[axis] == 0) or values.size == 0: result = values.sum(axis) result.fill(np.nan) else: result = values.max(axis) return _maybe_null_out(result, axis, mask)
def _nanmax(values, axis=None, skipna=True): mask = isnull(values) if skipna and not issubclass(values.dtype.type, (np.integer, np.datetime64)): values = values.copy() np.putmask(values, mask, -np.inf) # numpy 1.6.1 workaround in Python 3.x if values.dtype == np.object_ and sys.version_info[0] >= 3: # pragma: no cover import __builtin__ if values.ndim > 1: apply_ax = axis if axis is not None else 0 result = np.apply_along_axis(__builtin__.max, apply_ax, values) else: result = __builtin__.max(values) else: result = values.max(axis) return _maybe_null_out(result, axis, mask)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def get_corr_func(method): if method in ["kendall", "spearman"]: from scipy.stats import kendalltau, spearmanr def _pearson(a, b): return np.corrcoef(a, b)[0, 1] def _kendall(a, b): rs = kendalltau(a, b) if isinstance(rs, tuple): return rs[0] return rs def _spearman(a, b): return spearmanr(a, b)[0] _cor_methods = {"pearson": _pearson, "kendall": _kendall, "spearman": _spearman} return _cor_methods[method]
def get_corr_func(method): if method in ["kendall", "spearman"]: from scipy.stats import kendalltau, spearmanr def _pearson(a, b): return np.corrcoef(a, b)[0, 1] def _kendall(a, b): return kendalltau(a, b)[0] def _spearman(a, b): return spearmanr(a, b)[0] _cor_methods = {"pearson": _pearson, "kendall": _kendall, "spearman": _spearman} return _cor_methods[method]
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _kendall(a, b): rs = kendalltau(a, b) if isinstance(rs, tuple): return rs[0] return rs
def _kendall(a, b): return kendalltau(a, b)[0]
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def reindex( self, major=None, items=None, minor=None, method=None, major_axis=None, minor_axis=None, copy=True, ): """ Conform panel to new axis or axes Parameters ---------- major : Index or sequence, default None Can also use 'major_axis' keyword items : Index or sequence, default None minor : Index or sequence, default None Can also use 'minor_axis' keyword 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 copy : boolean, default True Return a new object, even if the passed indexes are the same Returns ------- Panel (new object) """ result = self major = _mut_exclusive(major, major_axis) minor = _mut_exclusive(minor, minor_axis) if ( method is None and not self._is_mixed_type and com._count_not_none(items, major, minor) == 3 ): return self._reindex_multi(items, major, minor) if major is not None: result = result._reindex_axis(major, method, 1, copy) if minor is not None: result = result._reindex_axis(minor, method, 2, copy) if items is not None: result = result._reindex_axis(items, method, 0, copy) if result is self and copy: raise ValueError("Must specify at least one axis") return result
def reindex( self, major=None, items=None, minor=None, method=None, major_axis=None, minor_axis=None, copy=True, ): """ Conform panel to new axis or axes Parameters ---------- major : Index or sequence, default None Can also use 'major_axis' keyword items : Index or sequence, default None minor : Index or sequence, default None Can also use 'minor_axis' keyword 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 copy : boolean, default True Return a new object, even if the passed indexes are the same Returns ------- Panel (new object) """ result = self major = _mut_exclusive(major, major_axis) minor = _mut_exclusive(minor, minor_axis) if major is not None: result = result._reindex_axis(major, method, 1, copy) if minor is not None: result = result._reindex_axis(minor, method, 2, copy) if items is not None: result = result._reindex_axis(items, method, 0, copy) if result is self and copy: raise ValueError("Must specify at least one axis") return result
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def block2d_to_block3d( values, items, shape, major_labels, minor_labels, ref_items=None ): """ Developer method for pivoting DataFrame -> Panel. Used in HDFStore and DataFrame.to_panel """ from pandas.core.internals import make_block panel_shape = (len(items),) + shape # TODO: lexsort depth needs to be 2!! # Create observation selection vector using major and minor # labels, for converting to panel format. selector = minor_labels + shape[1] * major_labels mask = np.zeros(np.prod(shape), dtype=bool) mask.put(selector, True) pvalues = np.empty(panel_shape, dtype=values.dtype) if not issubclass(pvalues.dtype.type, (np.integer, np.bool_)): pvalues.fill(np.nan) elif not mask.all(): pvalues = com._maybe_upcast(pvalues) pvalues.fill(np.nan) values = values for i in xrange(len(items)): pvalues[i].flat[mask] = values[:, i] if ref_items is None: ref_items = items return make_block(pvalues, items, ref_items)
def block2d_to_block3d( values, items, shape, major_labels, minor_labels, ref_items=None ): """ Developer method for pivoting DataFrame -> Panel. Used in HDFStore and DataFrame.to_panel """ from pandas.core.internals import make_block panel_shape = (len(items),) + shape # TODO: lexsort depth needs to be 2!! # Create observation selection vector using major and minor # labels, for converting to panel format. selector = minor_labels + shape[1] * major_labels mask = np.zeros(np.prod(shape), dtype=bool) mask.put(selector, True) pvalues = np.empty(panel_shape, dtype=values.dtype) if not issubclass(pvalues.dtype.type, np.integer): pvalues.fill(np.nan) values = values for i in xrange(len(items)): pvalues[i].flat[mask] = values[:, i] if ref_items is None: ref_items = items return make_block(pvalues, items, ref_items)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _insert_column(self, key): self.columns = self.columns.insert(len(self.columns), key)
def _insert_column(self, key): self.columns = Index(np.concatenate((self.columns, [key])))
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def __getitem__(self, key): """ Retrieve column or slice from DataFrame """ try: # unsure about how kludgy this is s = self._series[key] s.name = key return s except (TypeError, KeyError): if isinstance(key, slice): date_rng = self.index[key] return self.reindex(date_rng) elif isinstance(key, (np.ndarray, list)): if isinstance(key, list): key = lib.list_to_object_array(key) # also raises Exception if object array with NA values if com._is_bool_indexer(key): key = np.asarray(key, dtype=bool) return self._getitem_array(key) else: # pragma: no cover raise
def __getitem__(self, item): """ Retrieve column or slice from DataFrame """ try: # unsure about how kludgy this is s = self._series[item] s.name = item return s except (TypeError, KeyError): if isinstance(item, slice): date_rng = self.index[item] return self.reindex(date_rng) elif isinstance(item, np.ndarray): if len(item) != len(self.index): raise Exception( "Item wrong length %d instead of %d!" % (len(item), len(self.index)) ) newIndex = self.index[item] return self.reindex(newIndex) else: # pragma: no cover raise
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def ewma( arg, com=None, span=None, min_periods=0, freq=None, time_rule=None, adjust=True ): com = _get_center_of_mass(com, span) arg = _conv_timerule(arg, freq, time_rule) def _ewma(v): result = lib.ewma(v, com, int(adjust)) first_index = _first_valid_index(v) result[first_index : first_index + min_periods] = NaN return result return_hook, values = _process_data_structure(arg) output = np.apply_along_axis(_ewma, 0, values) return return_hook(output)
def ewma(arg, com=None, span=None, min_periods=0, freq=None, time_rule=None): com = _get_center_of_mass(com, span) arg = _conv_timerule(arg, freq, time_rule) def _ewma(v): result = _tseries.ewma(v, com) first_index = _first_valid_index(v) result[first_index : first_index + min_periods] = NaN return result return_hook, values = _process_data_structure(arg) output = np.apply_along_axis(_ewma, 0, values) return return_hook(output)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _ewma(v): result = lib.ewma(v, com, int(adjust)) first_index = _first_valid_index(v) result[first_index : first_index + min_periods] = NaN return result
def _ewma(v): result = _tseries.ewma(v, com) first_index = _first_valid_index(v) result[first_index : first_index + min_periods] = NaN return result
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def rolling_quantile( arg, window, quantile, min_periods=None, freq=None, time_rule=None ): """Moving quantile Parameters ---------- arg : Series, DataFrame window : Number of observations used for calculating statistic quantile : 0 <= quantile <= 1 min_periods : int Minimum number of observations in window required to have a value freq : None or string alias / date offset object, default=None Frequency to conform to before computing statistic Returns ------- y : type of input argument """ def call_cython(arg, window, minp): minp = _use_window(minp, window) return lib.roll_quantile(arg, window, minp, quantile) return _rolling_moment( arg, window, call_cython, min_periods, freq=freq, time_rule=time_rule )
def rolling_quantile( arg, window, quantile, min_periods=None, freq=None, time_rule=None ): """Moving quantile Parameters ---------- arg : Series, DataFrame window : Number of observations used for calculating statistic quantile : 0 <= quantile <= 1 min_periods : int Minimum number of observations in window required to have a value freq : None or string alias / date offset object, default=None Frequency to conform to before computing statistic Returns ------- y : type of input argument """ def call_cython(arg, window, minp): minp = _use_window(minp, window) return _tseries.roll_quantile(arg, window, minp, quantile) return _rolling_moment( arg, window, call_cython, min_periods, freq=freq, time_rule=time_rule )
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def call_cython(arg, window, minp): minp = _use_window(minp, window) return lib.roll_quantile(arg, window, minp, quantile)
def call_cython(arg, window, minp): minp = _use_window(minp, window) return _tseries.roll_quantile(arg, window, minp, quantile)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def rolling_apply(arg, window, func, min_periods=None, freq=None, time_rule=None): """Generic moving function application Parameters ---------- arg : Series, DataFrame window : Number of observations used for calculating statistic func : function Must produce a single value from an ndarray input min_periods : int Minimum number of observations in window required to have a value freq : None or string alias / date offset object, default=None Frequency to conform to before computing statistic Returns ------- y : type of input argument """ def call_cython(arg, window, minp): minp = _use_window(minp, window) return lib.roll_generic(arg, window, minp, func) return _rolling_moment( arg, window, call_cython, min_periods, freq=freq, time_rule=time_rule )
def rolling_apply(arg, window, func, min_periods=None, freq=None, time_rule=None): """Generic moving function application Parameters ---------- arg : Series, DataFrame window : Number of observations used for calculating statistic func : function Must produce a single value from an ndarray input min_periods : int Minimum number of observations in window required to have a value freq : None or string alias / date offset object, default=None Frequency to conform to before computing statistic Returns ------- y : type of input argument """ def call_cython(arg, window, minp): minp = _use_window(minp, window) return _tseries.roll_generic(arg, window, minp, func) return _rolling_moment( arg, window, call_cython, min_periods, freq=freq, time_rule=time_rule )
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def call_cython(arg, window, minp): minp = _use_window(minp, window) return lib.roll_generic(arg, window, minp, func)
def call_cython(arg, window, minp): minp = _use_window(minp, window) return _tseries.roll_generic(arg, window, minp, func)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def scatter_matrix( frame, alpha=0.5, figsize=None, ax=None, grid=False, diagonal="hist", marker=".", **kwds, ): """ Draw a matrix of scatter plots. Parameters ---------- alpha : amount of transparency applied figsize : a tuple (width, height) in inches ax : Matplotlib axis object grid : setting this to True will show the grid diagonal : pick between 'kde' and 'hist' for either Kernel Density Estimation or Histogram plon in the diagonal kwds : other plotting keyword arguments To be passed to scatter function Examples -------- >>> df = DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D']) >>> scatter_matrix(df, alpha=0.2) """ from matplotlib.artist import setp df = frame._get_numeric_data() n = df.columns.size fig, axes = _subplots(nrows=n, ncols=n, figsize=figsize, ax=ax, squeeze=False) # no gaps between subplots fig.subplots_adjust(wspace=0, hspace=0) mask = com.notnull(df) marker = _get_marker_compat(marker) for i, a in zip(range(n), df.columns): for j, b in zip(range(n), df.columns): ax = axes[i, j] if i == j: values = df[a].values[mask[a].values] # Deal with the diagonal by drawing a histogram there. if diagonal == "hist": ax.hist(values) elif diagonal in ("kde", "density"): from scipy.stats import gaussian_kde y = values gkde = gaussian_kde(y) ind = np.linspace(y.min(), y.max(), 1000) ax.plot(ind, gkde.evaluate(ind), **kwds) else: common = (mask[a] & mask[b]).values ax.scatter( df[b][common], df[a][common], marker=marker, alpha=alpha, **kwds ) ax.set_xlabel("") ax.set_ylabel("") ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) # setup labels if i == 0 and j % 2 == 1: ax.set_xlabel(b, visible=True) ax.xaxis.set_visible(True) ax.set_xlabel(b) ax.xaxis.set_ticks_position("top") ax.xaxis.set_label_position("top") setp(ax.get_xticklabels(), rotation=90) elif i == n - 1 and j % 2 == 0: ax.set_xlabel(b, visible=True) ax.xaxis.set_visible(True) ax.set_xlabel(b) ax.xaxis.set_ticks_position("bottom") ax.xaxis.set_label_position("bottom") setp(ax.get_xticklabels(), rotation=90) elif j == 0 and i % 2 == 0: ax.set_ylabel(a, visible=True) ax.yaxis.set_visible(True) ax.set_ylabel(a) ax.yaxis.set_ticks_position("left") ax.yaxis.set_label_position("left") elif j == n - 1 and i % 2 == 1: ax.set_ylabel(a, visible=True) ax.yaxis.set_visible(True) ax.set_ylabel(a) ax.yaxis.set_ticks_position("right") ax.yaxis.set_label_position("right") # ax.grid(b=grid) axes[0, 0].yaxis.set_visible(False) axes[n - 1, n - 1].xaxis.set_visible(False) axes[n - 1, n - 1].yaxis.set_visible(False) axes[0, n - 1].yaxis.tick_right() for ax in axes.flat: setp(ax.get_xticklabels(), fontsize=8) setp(ax.get_yticklabels(), fontsize=8) return axes
def scatter_matrix( frame, alpha=0.5, figsize=None, ax=None, grid=False, diagonal="hist", marker=".", **kwds, ): """ Draw a matrix of scatter plots. Parameters ---------- alpha : amount of transparency applied figsize : a tuple (width, height) in inches ax : Matplotlib axis object grid : setting this to True will show the grid diagonal : pick between 'kde' and 'hist' for either Kernel Density Estimation or Histogram plon in the diagonal kwds : other plotting keyword arguments To be passed to scatter function Examples -------- >>> df = DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D']) >>> scatter_matrix(df, alpha=0.2) """ df = frame._get_numeric_data() n = df.columns.size fig, axes = _subplots(nrows=n, ncols=n, figsize=figsize, ax=ax, squeeze=False) # no gaps between subplots fig.subplots_adjust(wspace=0, hspace=0) mask = com.notnull(df) marker = _get_marker_compat(marker) for i, a in zip(range(n), df.columns): for j, b in zip(range(n), df.columns): if i == j: values = df[a].values[mask[a].values] # Deal with the diagonal by drawing a histogram there. if diagonal == "hist": axes[i, j].hist(values) elif diagonal in ("kde", "density"): from scipy.stats import gaussian_kde y = values gkde = gaussian_kde(y) ind = np.linspace(y.min(), y.max(), 1000) axes[i, j].plot(ind, gkde.evaluate(ind), **kwds) else: common = (mask[a] & mask[b]).values axes[i, j].scatter( df[b][common], df[a][common], marker=marker, alpha=alpha, **kwds ) axes[i, j].set_xlabel("") axes[i, j].set_ylabel("") axes[i, j].set_xticklabels([]) axes[i, j].set_yticklabels([]) ticks = df.index is_datetype = ticks.inferred_type in ("datetime", "date", "datetime64") if ticks.is_numeric() or is_datetype: """ Matplotlib supports numeric values or datetime objects as xaxis values. Taking LBYL approach here, by the time matplotlib raises exception when using non numeric/datetime values for xaxis, several actions are already taken by plt. """ ticks = ticks._mpl_repr() # setup labels if i == 0 and j % 2 == 1: axes[i, j].set_xlabel(b, visible=True) # axes[i, j].xaxis.set_visible(True) axes[i, j].set_xlabel(b) axes[i, j].set_xticklabels(ticks) axes[i, j].xaxis.set_ticks_position("top") axes[i, j].xaxis.set_label_position("top") if i == n - 1 and j % 2 == 0: axes[i, j].set_xlabel(b, visible=True) # axes[i, j].xaxis.set_visible(True) axes[i, j].set_xlabel(b) axes[i, j].set_xticklabels(ticks) axes[i, j].xaxis.set_ticks_position("bottom") axes[i, j].xaxis.set_label_position("bottom") if j == 0 and i % 2 == 0: axes[i, j].set_ylabel(a, visible=True) # axes[i, j].yaxis.set_visible(True) axes[i, j].set_ylabel(a) axes[i, j].set_yticklabels(ticks) axes[i, j].yaxis.set_ticks_position("left") axes[i, j].yaxis.set_label_position("left") if j == n - 1 and i % 2 == 1: axes[i, j].set_ylabel(a, visible=True) # axes[i, j].yaxis.set_visible(True) axes[i, j].set_ylabel(a) axes[i, j].set_yticklabels(ticks) axes[i, j].yaxis.set_ticks_position("right") axes[i, j].yaxis.set_label_position("right") axes[i, j].grid(b=grid) return axes
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def __init__( self, data, kind=None, by=None, subplots=False, sharex=True, sharey=False, use_index=True, figsize=None, grid=None, legend=True, rot=None, ax=None, fig=None, title=None, xlim=None, ylim=None, xticks=None, yticks=None, sort_columns=False, fontsize=None, secondary_y=False, **kwds, ): self.data = data self.by = by self.kind = kind self.sort_columns = sort_columns self.subplots = subplots self.sharex = sharex self.sharey = sharey self.figsize = figsize self.xticks = xticks self.yticks = yticks self.xlim = xlim self.ylim = ylim self.title = title self.use_index = use_index self.fontsize = fontsize self.rot = rot if grid is None: grid = False if secondary_y else True self.grid = grid self.legend = legend for attr in self._pop_attributes: value = kwds.pop(attr, self._attr_defaults.get(attr, None)) setattr(self, attr, value) self.ax = ax self.fig = fig self.axes = None if not isinstance(secondary_y, (bool, tuple, list, np.ndarray)): secondary_y = [secondary_y] self.secondary_y = secondary_y self.kwds = kwds
def __init__( self, data, kind=None, by=None, subplots=False, sharex=True, sharey=False, use_index=True, figsize=None, grid=None, legend=True, rot=None, ax=None, fig=None, title=None, xlim=None, ylim=None, xticks=None, yticks=None, sort_columns=False, fontsize=None, secondary_y=False, **kwds, ): self.data = data self.by = by self.kind = kind self.sort_columns = sort_columns self.subplots = subplots self.sharex = sharex self.sharey = sharey self.figsize = figsize self.xticks = xticks self.yticks = yticks self.xlim = xlim self.ylim = ylim self.title = title self.use_index = use_index self.fontsize = fontsize self.rot = rot if grid is None: grid = False if secondary_y else True self.grid = grid self.legend = legend for attr in self._pop_attributes: value = kwds.pop(attr, self._attr_defaults.get(attr, None)) setattr(self, attr, value) self.ax = ax self.fig = fig self.axes = None self.secondary_y = secondary_y self.kwds = kwds
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _iter_data(self): from pandas.core.frame import DataFrame if isinstance(self.data, (Series, np.ndarray)): yield self.label, np.asarray(self.data) elif isinstance(self.data, DataFrame): df = self.data if self.sort_columns: columns = com._try_sort(df.columns) else: columns = df.columns for col in columns: empty = df[col].count() == 0 # is this right? values = df[col].values if not empty else np.zeros(len(df)) yield col, values
def _iter_data(self): from pandas.core.frame import DataFrame if isinstance(self.data, (Series, np.ndarray)): yield com._stringify(self.label), np.asarray(self.data) elif isinstance(self.data, DataFrame): df = self.data if self.sort_columns: columns = com._try_sort(df.columns) else: columns = df.columns for col in columns: empty = df[col].count() == 0 # is this right? values = df[col].values if not empty else np.zeros(len(df)) col = com._stringify(col) yield col, values
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _maybe_right_yaxis(self, ax): _types = (list, tuple, np.ndarray) sec_true = isinstance(self.secondary_y, bool) and self.secondary_y list_sec = isinstance(self.secondary_y, _types) has_sec = list_sec and len(self.secondary_y) > 0 all_sec = list_sec and len(self.secondary_y) == self.nseries if (sec_true or has_sec) and not hasattr(ax, "right_ax"): orig_ax, new_ax = ax, ax.twinx() orig_ax.right_ax, new_ax.left_ax = new_ax, orig_ax if len(orig_ax.get_lines()) == 0: # no data on left y orig_ax.get_yaxis().set_visible(False) if len(new_ax.get_lines()) == 0: new_ax.get_yaxis().set_visible(False) if sec_true or all_sec: ax = new_ax else: ax.get_yaxis().set_visible(True) return ax
def _maybe_right_yaxis(self, ax): ypos = ax.get_yaxis().get_ticks_position().strip().lower() if self.secondary_y and ypos != "right": orig_ax = ax ax = ax.twinx() if len(orig_ax.get_lines()) == 0: # no data on left y orig_ax.get_yaxis().set_visible(False) else: ax.get_yaxis().set_visible(True) return ax
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _setup_subplots(self): if self.subplots: nrows, ncols = self._get_layout() if self.ax is None: fig, axes = _subplots( nrows=nrows, ncols=ncols, sharex=self.sharex, sharey=self.sharey, figsize=self.figsize, secondary_y=self.secondary_y, data=self.data, ) else: fig, axes = _subplots( nrows=nrows, ncols=ncols, sharex=self.sharex, sharey=self.sharey, figsize=self.figsize, ax=self.ax, secondary_y=self.secondary_y, data=self.data, ) else: if self.ax is None: fig = self.plt.figure(figsize=self.figsize) ax = fig.add_subplot(111) ax = self._maybe_right_yaxis(ax) else: fig = self.ax.get_figure() ax = self._maybe_right_yaxis(self.ax) axes = [ax] self.fig = fig self.axes = axes
def _setup_subplots(self): if self.subplots: nrows, ncols = self._get_layout() if self.ax is None: fig, axes = _subplots( nrows=nrows, ncols=ncols, sharex=self.sharex, sharey=self.sharey, figsize=self.figsize, secondary_y=self.secondary_y, data=self.data, ) else: fig, axes = _subplots( nrows=nrows, ncols=ncols, sharex=self.sharex, sharey=self.sharey, figsize=self.figsize, ax=self.ax, secondary_y=self.secondary_y, data=self.data, ) else: if self.ax is None: fig = self.plt.figure(figsize=self.figsize) ax = fig.add_subplot(111) ax = self._maybe_right_yaxis(ax) self.ax = ax else: fig = self.ax.get_figure() self.ax = self._maybe_right_yaxis(self.ax) axes = [self.ax] self.fig = fig self.axes = axes
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _adorn_subplots(self): to_adorn = self.axes # todo: sharex, sharey handling? for ax in to_adorn: if self.yticks is not None: ax.set_yticks(self.yticks) if self.xticks is not None: ax.set_xticks(self.xticks) if self.ylim is not None: ax.set_ylim(self.ylim) if self.xlim is not None: ax.set_xlim(self.xlim) ax.grid(self.grid) if self.title: if self.subplots: self.fig.suptitle(self.title) else: self.axes[0].set_title(self.title) if self._need_to_set_index: labels = [_stringify(key) for key in self.data.index] labels = dict(zip(range(len(self.data.index)), labels)) for ax_ in self.axes: # ax_.set_xticks(self.xticks) xticklabels = [labels.get(x, "") for x in ax_.get_xticks()] ax_.set_xticklabels(xticklabels, rotation=self.rot)
def _adorn_subplots(self): if self.subplots: to_adorn = self.axes else: to_adorn = [self.ax] # todo: sharex, sharey handling? for ax in to_adorn: if self.yticks is not None: ax.set_yticks(self.yticks) if self.xticks is not None: ax.set_xticks(self.xticks) if self.ylim is not None: ax.set_ylim(self.ylim) if self.xlim is not None: ax.set_xlim(self.xlim) ax.grid(self.grid) if self.legend and not self.subplots: self.ax.legend(loc="best", title=self.legend_title) if self.title: if self.subplots: self.fig.suptitle(self.title) else: self.ax.set_title(self.title) if self._need_to_set_index: labels = [_stringify(key) for key in self.data.index] labels = dict(zip(range(len(self.data.index)), labels)) for ax_ in self.axes: # ax_.set_xticks(self.xticks) xticklabels = [labels.get(x, "") for x in ax_.get_xticks()] ax_.set_xticklabels(xticklabels, rotation=self.rot)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _make_plot(self): from scipy.stats import gaussian_kde plotf = self._get_plot_function() for i, (label, y) in enumerate(self._iter_data()): ax = self._get_ax(i) style = self._get_style(i, label) label = com._stringify(label) gkde = gaussian_kde(y) sample_range = max(y) - min(y) ind = np.linspace( min(y) - 0.5 * sample_range, max(y) + 0.5 * sample_range, 1000 ) ax.set_ylabel("Density") plotf(ax, ind, gkde.evaluate(ind), style, label=label, **self.kwds) ax.grid(self.grid)
def _make_plot(self): from scipy.stats import gaussian_kde plotf = self._get_plot_function() for i, (label, y) in enumerate(self._iter_data()): ax, style = self._get_ax_and_style(i) if self.style: style = self.style gkde = gaussian_kde(y) sample_range = max(y) - min(y) ind = np.linspace( min(y) - 0.5 * sample_range, max(y) + 0.5 * sample_range, 1000 ) ax.set_ylabel("Density") plotf(ax, ind, gkde.evaluate(ind), style, label=label, **self.kwds) ax.grid(self.grid)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _post_plot_logic(self): df = self.data if self.subplots and self.legend: for ax in self.axes: ax.legend(loc="best")
def _post_plot_logic(self): df = self.data if self.subplots and self.legend: self.axes[0].legend(loc="best")
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def __init__(self, data, **kwargs): self.mark_right = kwargs.pop("mark_right", True) MPLPlot.__init__(self, data, **kwargs)
def __init__(self, data, **kwargs): MPLPlot.__init__(self, data, **kwargs)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _use_dynamic_x(self): freq = self._index_freq() ax = self._get_ax(0) ax_freq = getattr(ax, "freq", None) if freq is None: # convert irregular if axes has freq info freq = ax_freq else: # do not use tsplot if irregular was plotted first if (ax_freq is None) and (len(ax.get_lines()) > 0): return False return (freq is not None) and self._is_dynamic_freq(freq)
def _use_dynamic_x(self): freq = self._index_freq() ax, _ = self._get_ax_and_style(0) ax_freq = getattr(ax, "freq", None) if freq is None: # convert irregular if axes has freq info freq = ax_freq else: # do not use tsplot if irregular was plotted first if (ax_freq is None) and (len(ax.get_lines()) > 0): return False return (freq is not None) and self._is_dynamic_freq(freq)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _make_plot(self): # this is slightly deceptive if self.use_index and self._use_dynamic_x(): data = self._maybe_convert_index(self.data) self._make_ts_plot(data, **self.kwds) else: import matplotlib.pyplot as plt cycle = "".join(plt.rcParams.get("axes.color_cycle", list("bgrcmyk"))) colors = self.kwds.pop("colors", cycle) lines = [] labels = [] x = self._get_xticks(convert_period=True) plotf = self._get_plot_function() for i, (label, y) in enumerate(self._iter_data()): ax = self._get_ax(i) style = self._get_style(i, label) kwds = self.kwds.copy() if re.match("[a-z]+", style) is None: kwds["color"] = colors[i % len(colors)] label = com._stringify(label) mask = com.isnull(y) if mask.any(): y = np.ma.array(y) y = np.ma.masked_where(mask, y) newline = plotf(ax, x, y, style, label=label, **kwds)[0] lines.append(newline) leg_label = label if self.mark_right and self.on_right(i): leg_label += " (right)" labels.append(leg_label) ax.grid(self.grid) self._make_legend(lines, labels)
def _make_plot(self): # this is slightly deceptive if self.use_index and self._use_dynamic_x(): data = self._maybe_convert_index(self.data) self._make_ts_plot(data) else: x = self._get_xticks(convert_period=True) plotf = self._get_plot_function() for i, (label, y) in enumerate(self._iter_data()): ax, style = self._get_ax_and_style(i) if self.style: style = self.style mask = com.isnull(y) if mask.any(): y = np.ma.array(y) y = np.ma.masked_where(mask, y) plotf(ax, x, y, style, label=label, **self.kwds) ax.grid(self.grid)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _make_ts_plot(self, data, **kwargs): from pandas.tseries.plotting import tsplot import matplotlib.pyplot as plt kwargs = kwargs.copy() cycle = "".join(plt.rcParams.get("axes.color_cycle", list("bgrcmyk"))) colors = kwargs.pop("colors", "".join(cycle)) plotf = self._get_plot_function() lines = [] labels = [] def to_leg_label(label, i): if self.mark_right and self.on_right(i): return label + " (right)" return label if isinstance(data, Series): ax = self._get_ax(0) # self.axes[0] style = self.style or "" label = com._stringify(self.label) if re.match("[a-z]+", style) is None: kwargs["color"] = colors[0] newlines = tsplot(data, plotf, ax=ax, label=label, style=self.style, **kwargs) ax.grid(self.grid) lines.append(newlines[0]) leg_label = to_leg_label(label, 0) labels.append(leg_label) else: for i, col in enumerate(data.columns): label = com._stringify(col) ax = self._get_ax(i) style = self._get_style(i, col) kwds = kwargs.copy() if re.match("[a-z]+", style) is None: kwds["color"] = colors[i % len(colors)] newlines = tsplot(data[col], plotf, ax=ax, label=label, style=style, **kwds) lines.append(newlines[0]) leg_label = to_leg_label(label, i) labels.append(leg_label) ax.grid(self.grid) self._make_legend(lines, labels)
def _make_ts_plot(self, data, **kwargs): from pandas.tseries.plotting import tsplot plotf = self._get_plot_function() if isinstance(data, Series): ax, _ = self._get_ax_and_style(0) # self.axes[0] label = com._stringify(self.label) tsplot(data, plotf, ax=ax, label=label, style=self.style, **kwargs) ax.grid(self.grid) else: for i, col in enumerate(data.columns): ax, _ = self._get_ax_and_style(i) label = com._stringify(col) tsplot(data[col], plotf, ax=ax, label=label, **kwargs) ax.grid(self.grid)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _maybe_convert_index(self, data): # tsplot converts automatically, but don't want to convert index # over and over for DataFrames from pandas.core.frame import DataFrame if isinstance(data.index, DatetimeIndex) and isinstance(data, DataFrame): freq = getattr(data.index, "freq", None) if freq is None: freq = getattr(data.index, "inferred_freq", None) if isinstance(freq, DateOffset): freq = freq.rule_code freq = get_period_alias(freq) if freq is None: ax = self._get_ax(0) freq = getattr(ax, "freq", None) if freq is None: raise ValueError("Could not get frequency alias for plotting") data = DataFrame( data.values, index=data.index.to_period(freq=freq), columns=data.columns ) return data
def _maybe_convert_index(self, data): # tsplot converts automatically, but don't want to convert index # over and over for DataFrames from pandas.core.frame import DataFrame if isinstance(data.index, DatetimeIndex) and isinstance(data, DataFrame): freq = getattr(data.index, "freq", None) if freq is None: freq = getattr(data.index, "inferred_freq", None) if isinstance(freq, DateOffset): freq = freq.rule_code freq = get_period_alias(freq) if freq is None: ax, _ = self._get_ax_and_style(0) freq = getattr(ax, "freq", None) if freq is None: raise ValueError("Could not get frequency alias for plotting") data = DataFrame( data.values, index=data.index.to_period(freq=freq), columns=data.columns ) return data
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _post_plot_logic(self): df = self.data condition = ( not self._use_dynamic_x and df.index.is_all_dates and not self.subplots or (self.subplots and self.sharex) ) index_name = self._get_index_name() for ax in self.axes: if condition: format_date_labels(ax) if index_name is not None: ax.set_xlabel(index_name) if self.subplots and self.legend: for ax in self.axes: ax.legend(loc="best")
def _post_plot_logic(self): df = self.data if self.legend: if self.subplots: for ax in self.axes: ax.legend(loc="best") else: self.axes[0].legend(loc="best") condition = ( not self._use_dynamic_x and df.index.is_all_dates and not self.subplots or (self.subplots and self.sharex) ) index_name = self._get_index_name() for ax in self.axes: if condition: format_date_labels(ax) if index_name is not None: ax.set_xlabel(index_name)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _make_plot(self): colors = self.kwds.get("color", "brgyk") rects = [] labels = [] ax = self._get_ax(0) # self.axes[0] bar_f = self.bar_f pos_prior = neg_prior = np.zeros(len(self.data)) K = self.nseries for i, (label, y) in enumerate(self._iter_data()): label = com._stringify(label) kwds = self.kwds.copy() kwds["color"] = colors[i % len(colors)] if self.subplots: ax = self._get_ax(i) # self.axes[i] rect = bar_f(ax, self.ax_pos, y, 0.5, start=pos_prior, linewidth=1, **kwds) ax.set_title(label) elif self.stacked: mask = y > 0 start = np.where(mask, pos_prior, neg_prior) rect = bar_f( ax, self.ax_pos, y, 0.5, start=start, label=label, linewidth=1, **kwds ) pos_prior = pos_prior + np.where(mask, y, 0) neg_prior = neg_prior + np.where(mask, 0, y) else: rect = bar_f( ax, self.ax_pos + i * 0.75 / K, y, 0.75 / K, start=pos_prior, label=label, **kwds, ) rects.append(rect) labels.append(label) if self.legend and not self.subplots: patches = [r[0] for r in rects] self.axes[0].legend(patches, labels, loc="best", title=self.legend_title)
def _make_plot(self): colors = self.kwds.get("color", "brgyk") rects = [] labels = [] ax, _ = self._get_ax_and_style(0) # self.axes[0] bar_f = self.bar_f pos_prior = neg_prior = np.zeros(len(self.data)) K = self.nseries for i, (label, y) in enumerate(self._iter_data()): kwds = self.kwds.copy() kwds["color"] = colors[i % len(colors)] if self.subplots: ax, _ = self._get_ax_and_style(i) # self.axes[i] rect = bar_f(ax, self.ax_pos, y, 0.5, start=pos_prior, linewidth=1, **kwds) ax.set_title(label) elif self.stacked: mask = y > 0 start = np.where(mask, pos_prior, neg_prior) rect = bar_f( ax, self.ax_pos, y, 0.5, start=start, label=label, linewidth=1, **kwds ) pos_prior = pos_prior + np.where(mask, y, 0) neg_prior = neg_prior + np.where(mask, 0, y) else: rect = bar_f( ax, self.ax_pos + i * 0.75 / K, y, 0.75 / K, start=pos_prior, label=label, **kwds, ) rects.append(rect) labels.append(label) if self.legend and not self.subplots: patches = [r[0] for r in rects] # Legend to the right of the plot # ax.legend(patches, labels, bbox_to_anchor=(1.05, 1), # loc=2, borderaxespad=0.) # self.fig.subplots_adjust(right=0.80) ax.legend(patches, labels, loc="best", title=self.legend_title)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def plot_frame( frame=None, x=None, y=None, subplots=False, sharex=True, sharey=False, use_index=True, figsize=None, grid=False, legend=True, rot=None, ax=None, style=None, title=None, xlim=None, ylim=None, logy=False, xticks=None, yticks=None, kind="line", sort_columns=False, fontsize=None, secondary_y=False, **kwds, ): """ Make line or bar plot of DataFrame's series with the index on the x-axis using matplotlib / pylab. Parameters ---------- x : int or str, default None y : int or str, default None Allows plotting of one column versus another subplots : boolean, default False Make separate subplots for each time series sharex : boolean, default True In case subplots=True, share x axis sharey : boolean, default False In case subplots=True, share y axis 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 True Axis grid lines legend : boolean, default True Place legend on axis subplots ax : matplotlib axis object, default None style : list or dict matplotlib line style per column kind : {'line', 'bar', 'barh'} bar : vertical bar plot barh : horizontal bar plot logy : boolean, default False For line plots, use log scaling on y axis xticks : sequence Values to use for the xticks yticks : sequence Values to use for the yticks xlim : 2-tuple/list 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 dict then can select which columns to plot on secondary y-axis kwds : keywords Options to pass to matplotlib plotting method Returns ------- ax_or_axes : matplotlib.AxesSubplot or list of them """ kind = _get_standard_kind(kind.lower().strip()) if kind == "line": klass = LinePlot elif kind in ("bar", "barh"): klass = BarPlot elif kind == "kde": klass = KdePlot else: raise ValueError("Invalid chart type given %s" % kind) if isinstance(x, int): x = frame.columns[x] if isinstance(y, int): y = frame.columns[y] if x is not None: frame = frame.set_index(x).sort_index() if y is not None: return plot_series( frame[y], label=y, kind=kind, use_index=True, rot=rot, xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim, ax=ax, style=style, grid=grid, logy=logy, secondary_y=secondary_y, **kwds, ) 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, logy=logy, sort_columns=sort_columns, secondary_y=secondary_y, **kwds, ) plot_obj.generate() plot_obj.draw() if subplots: return plot_obj.axes else: return plot_obj.axes[0]
def plot_frame( frame=None, subplots=False, sharex=True, sharey=False, use_index=True, figsize=None, grid=False, legend=True, rot=None, ax=None, title=None, xlim=None, ylim=None, logy=False, xticks=None, yticks=None, kind="line", sort_columns=False, fontsize=None, secondary_y=False, **kwds, ): """ Make line or bar plot of DataFrame's series with the index on the x-axis using matplotlib / pylab. Parameters ---------- subplots : boolean, default False Make separate subplots for each time series sharex : boolean, default True In case subplots=True, share x axis sharey : boolean, default False In case subplots=True, share y axis 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 True Axis grid lines legend : boolean, default True Place legend on axis subplots ax : matplotlib axis object, default None kind : {'line', 'bar', 'barh'} bar : vertical bar plot barh : horizontal bar plot logy : boolean, default False For line plots, use log scaling on y axis xticks : sequence Values to use for the xticks yticks : sequence Values to use for the yticks xlim : 2-tuple/list 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 dict then can select which columns to plot on secondary y-axis kwds : keywords Options to pass to matplotlib plotting method Returns ------- ax_or_axes : matplotlib.AxesSubplot or list of them """ kind = _get_standard_kind(kind.lower().strip()) if kind == "line": klass = LinePlot elif kind in ("bar", "barh"): klass = BarPlot elif kind == "kde": klass = KdePlot else: raise ValueError("Invalid chart type given %s" % kind) plot_obj = klass( frame, kind=kind, subplots=subplots, rot=rot, legend=legend, ax=ax, fontsize=fontsize, use_index=use_index, sharex=sharex, sharey=sharey, xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim, title=title, grid=grid, figsize=figsize, logy=logy, sort_columns=sort_columns, secondary_y=secondary_y, **kwds, ) plot_obj.generate() plot_obj.draw() if subplots: return plot_obj.axes else: return plot_obj.axes[0]
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def boxplot( data, column=None, by=None, ax=None, fontsize=None, rot=0, grid=True, figsize=None, **kwds, ): """ Make a box plot from DataFrame column optionally grouped b ysome columns or other inputs Parameters ---------- data : DataFrame or Series column : column name or list of names, or vector Can be any valid input to groupby by : string or sequence Column in the DataFrame to group by fontsize : int or string rot : label rotation angle kwds : other plotting keyword arguments to be passed to matplotlib boxplot function Returns ------- ax : matplotlib.axes.AxesSubplot """ from pandas import Series, DataFrame if isinstance(data, Series): data = DataFrame({"x": data}) column = "x" def plot_group(grouped, ax): keys, values = zip(*grouped) keys = [_stringify(x) for x in keys] values = [remove_na(v) for v in values] ax.boxplot(values, **kwds) if kwds.get("vert", 1): ax.set_xticklabels(keys, rotation=rot, fontsize=fontsize) else: ax.set_yticklabels(keys, rotation=rot, fontsize=fontsize) if column == None: columns = None else: if isinstance(column, (list, tuple)): columns = column else: columns = [column] if by is not None: if not isinstance(by, (list, tuple)): by = [by] fig, axes = _grouped_plot_by_column( plot_group, data, columns=columns, by=by, grid=grid, figsize=figsize, ax=ax ) # Return axes in multiplot case, maybe revisit later # 985 ret = axes else: if ax is None: ax = _gca() fig = ax.get_figure() data = data._get_numeric_data() if columns: cols = columns else: cols = data.columns keys = [_stringify(x) for x in cols] # Return boxplot dict in single plot case clean_values = [remove_na(x) for x in data[cols].values.T] bp = ax.boxplot(clean_values, **kwds) if kwds.get("vert", 1): ax.set_xticklabels(keys, rotation=rot, fontsize=fontsize) else: ax.set_yticklabels(keys, rotation=rot, fontsize=fontsize) ax.grid(grid) ret = bp fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2) return ret
def boxplot( data, column=None, by=None, ax=None, fontsize=None, rot=0, grid=True, figsize=None, **kwds, ): """ Make a box plot from DataFrame column optionally grouped b ysome columns or other inputs Parameters ---------- data : DataFrame or Series column : column name or list of names, or vector Can be any valid input to groupby by : string or sequence Column in the DataFrame to group by fontsize : int or string rot : label rotation angle kwds : other plotting keyword arguments to be passed to matplotlib boxplot function Returns ------- ax : matplotlib.axes.AxesSubplot """ from pandas import Series, DataFrame if isinstance(data, Series): data = DataFrame({"x": data}) column = "x" def plot_group(grouped, ax): keys, values = zip(*grouped) keys = [_stringify(x) for x in keys] values = [remove_na(v) for v in values] ax.boxplot(values, **kwds) if kwds.get("vert", 1): ax.set_xticklabels(keys, rotation=rot, fontsize=fontsize) else: ax.set_yticklabels(keys, rotation=rot, fontsize=fontsize) if column == None: columns = None else: if isinstance(column, (list, tuple)): columns = column else: columns = [column] if by is not None: if not isinstance(by, (list, tuple)): by = [by] fig, axes = _grouped_plot_by_column( plot_group, data, columns=columns, by=by, grid=grid, figsize=figsize ) # Return axes in multiplot case, maybe revisit later # 985 ret = axes else: if ax is None: ax = _gca() fig = ax.get_figure() data = data._get_numeric_data() if columns: cols = columns else: cols = data.columns keys = [_stringify(x) for x in cols] # Return boxplot dict in single plot case clean_values = [remove_na(x) for x in data[cols].values.T] bp = ax.boxplot(clean_values, **kwds) if kwds.get("vert", 1): ax.set_xticklabels(keys, rotation=rot, fontsize=fontsize) else: ax.set_yticklabels(keys, rotation=rot, fontsize=fontsize) ax.grid(grid) ret = bp fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2) return ret
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _subplots( nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, ax=None, secondary_y=False, data=None, **fig_kw, ): """Create a figure with a set of subplots already made. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call. Keyword arguments: nrows : int Number of rows of the subplot grid. Defaults to 1. ncols : int Number of columns of the subplot grid. Defaults to 1. sharex : bool If True, the X axis will be shared amongst all subplots. sharey : bool If True, the Y axis will be shared amongst all subplots. squeeze : bool If True, extra dimensions are squeezed out from the returned axis object: - if only one subplot is constructed (nrows=ncols=1), the resulting single Axis object is returned as a scalar. - for Nx1 or 1xN subplots, the returned object is a 1-d numpy object array of Axis objects are returned as numpy 1-d arrays. - for NxM subplots with N>1 and M>1 are returned as a 2d array. If False, no squeezing at all is done: the returned axis object is always a 2-d array contaning Axis instances, even if it ends up being 1x1. subplot_kw : dict Dict with keywords passed to the add_subplot() call used to create each subplots. fig_kw : dict Dict with keywords passed to the figure() call. Note that all keywords not recognized above will be automatically included here. ax : Matplotlib axis object, default None secondary_y : boolean or sequence of ints, default False If True then y-axis will be on the right Returns: fig, ax : tuple - fig is the Matplotlib Figure object - ax can be either a single axis object or an array of axis objects if more than one supblot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above. **Examples:** x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) # Just a figure and one subplot f, ax = plt.subplots() ax.plot(x, y) ax.set_title('Simple plot') # Two subplots, unpack the output array immediately f, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ax1.plot(x, y) ax1.set_title('Sharing Y axis') ax2.scatter(x, y) # Four polar axes plt.subplots(2, 2, subplot_kw=dict(polar=True)) """ import matplotlib.pyplot as plt from pandas.core.frame import DataFrame if subplot_kw is None: subplot_kw = {} if ax is None: fig = plt.figure(**fig_kw) else: fig = ax.get_figure() fig.clear() # Create empty object array to hold all axes. It's easiest to make it 1-d # so we can just append subplots upon creation, and then nplots = nrows * ncols axarr = np.empty(nplots, dtype=object) def on_right(i): if isinstance(secondary_y, bool): return secondary_y if isinstance(data, DataFrame): return data.columns[i] in secondary_y # Create first subplot separately, so we can share it if requested ax0 = fig.add_subplot(nrows, ncols, 1, **subplot_kw) if on_right(0): orig_ax = ax0 ax0 = ax0.twinx() orig_ax.get_yaxis().set_visible(False) orig_ax.right_ax = ax0 ax0.left_ax = orig_ax if sharex: subplot_kw["sharex"] = ax0 if sharey: subplot_kw["sharey"] = ax0 axarr[0] = ax0 # Note off-by-one counting because add_subplot uses the MATLAB 1-based # convention. for i in range(1, nplots): ax = fig.add_subplot(nrows, ncols, i + 1, **subplot_kw) if on_right(i): orig_ax = ax ax = ax.twinx() orig_ax.get_yaxis().set_visible(False) axarr[i] = ax if nplots > 1: if sharex and nrows > 1: for i, ax in enumerate(axarr): if np.ceil(float(i + 1) / ncols) < nrows: # only last row [label.set_visible(False) for label in ax.get_xticklabels()] if sharey and ncols > 1: for i, ax in enumerate(axarr): if (i % ncols) != 0: # only first column [label.set_visible(False) for label in ax.get_yticklabels()] if squeeze: # Reshape the array to have the final desired dimension (nrow,ncol), # though discarding unneeded dimensions that equal 1. If we only have # one subplot, just return it instead of a 1-element array. if nplots == 1: axes = axarr[0] else: axes = axarr.reshape(nrows, ncols).squeeze() else: # returned axis array will be always 2-d, even if nrows=ncols=1 axes = axarr.reshape(nrows, ncols) return fig, axes
def _subplots( nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, ax=None, secondary_y=False, data=None, **fig_kw, ): """Create a figure with a set of subplots already made. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call. Keyword arguments: nrows : int Number of rows of the subplot grid. Defaults to 1. ncols : int Number of columns of the subplot grid. Defaults to 1. sharex : bool If True, the X axis will be shared amongst all subplots. sharey : bool If True, the Y axis will be shared amongst all subplots. squeeze : bool If True, extra dimensions are squeezed out from the returned axis object: - if only one subplot is constructed (nrows=ncols=1), the resulting single Axis object is returned as a scalar. - for Nx1 or 1xN subplots, the returned object is a 1-d numpy object array of Axis objects are returned as numpy 1-d arrays. - for NxM subplots with N>1 and M>1 are returned as a 2d array. If False, no squeezing at all is done: the returned axis object is always a 2-d array contaning Axis instances, even if it ends up being 1x1. subplot_kw : dict Dict with keywords passed to the add_subplot() call used to create each subplots. fig_kw : dict Dict with keywords passed to the figure() call. Note that all keywords not recognized above will be automatically included here. ax : Matplotlib axis object, default None secondary_y : boolean or sequence of ints, default False If True then y-axis will be on the right Returns: fig, ax : tuple - fig is the Matplotlib Figure object - ax can be either a single axis object or an array of axis objects if more than one supblot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above. **Examples:** x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) # Just a figure and one subplot f, ax = plt.subplots() ax.plot(x, y) ax.set_title('Simple plot') # Two subplots, unpack the output array immediately f, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ax1.plot(x, y) ax1.set_title('Sharing Y axis') ax2.scatter(x, y) # Four polar axes plt.subplots(2, 2, subplot_kw=dict(polar=True)) """ import matplotlib.pyplot as plt from pandas.core.frame import DataFrame if subplot_kw is None: subplot_kw = {} if ax is None: fig = plt.figure(**fig_kw) else: fig = ax.get_figure() fig.clear() # Create empty object array to hold all axes. It's easiest to make it 1-d # so we can just append subplots upon creation, and then nplots = nrows * ncols axarr = np.empty(nplots, dtype=object) def on_right(i): if isinstance(secondary_y, bool): return secondary_y if isinstance(data, DataFrame): return data.columns[i] in secondary_y # Create first subplot separately, so we can share it if requested ax0 = fig.add_subplot(nrows, ncols, 1, **subplot_kw) if on_right(0): orig_ax = ax0 ax0 = ax0.twinx() orig_ax.get_yaxis().set_visible(False) if sharex: subplot_kw["sharex"] = ax0 if sharey: subplot_kw["sharey"] = ax0 axarr[0] = ax0 # Note off-by-one counting because add_subplot uses the MATLAB 1-based # convention. for i in range(1, nplots): ax = fig.add_subplot(nrows, ncols, i + 1, **subplot_kw) if on_right(i): orig_ax = ax ax = ax.twinx() orig_ax.get_yaxis().set_visible(False) axarr[i] = ax if nplots > 1: if sharex and nrows > 1: for i, ax in enumerate(axarr): if np.ceil(float(i + 1) / ncols) < nrows: # only last row [label.set_visible(False) for label in ax.get_xticklabels()] if sharey and ncols > 1: for i, ax in enumerate(axarr): if (i % ncols) != 0: # only first column [label.set_visible(False) for label in ax.get_yticklabels()] if squeeze: # Reshape the array to have the final desired dimension (nrow,ncol), # though discarding unneeded dimensions that equal 1. If we only have # one subplot, just return it instead of a 1-element array. if nplots == 1: axes = axarr[0] else: axes = axarr.reshape(nrows, ncols).squeeze() else: # returned axis array will be always 2-d, even if nrows=ncols=1 axes = axarr.reshape(nrows, ncols) return fig, axes
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def __new__( cls, data=None, freq=None, start=None, end=None, periods=None, copy=False, name=None, tz=None, verify_integrity=True, normalize=False, **kwds, ): warn = False if "offset" in kwds and kwds["offset"]: freq = kwds["offset"] warn = True freq_infer = False if not isinstance(freq, DateOffset): if freq != "infer": freq = to_offset(freq) else: freq_infer = True freq = None if warn: import warnings warnings.warn( "parameter 'offset' is deprecated, please use 'freq' instead", FutureWarning ) offset = freq if periods is not None: if com.is_float(periods): periods = int(periods) elif not com.is_integer(periods): raise ValueError("Periods must be a number, got %s" % str(periods)) if data is None and offset is None: raise ValueError("Must provide freq argument if no data is supplied") if data is None: return cls._generate( start, end, periods, name, offset, tz=tz, normalize=normalize ) if not isinstance(data, np.ndarray): if np.isscalar(data): raise ValueError( "DatetimeIndex() must be called with a " "collection of some kind, %s was passed" % repr(data) ) # other iterable of some kind if not isinstance(data, (list, tuple)): data = list(data) data = np.asarray(data, dtype="O") # try a few ways to make it datetime64 if lib.is_string_array(data): data = _str_to_dt_array(data, offset) else: data = tools.to_datetime(data) data.offset = offset if issubclass(data.dtype.type, basestring): subarr = _str_to_dt_array(data, offset) elif issubclass(data.dtype.type, np.datetime64): if isinstance(data, DatetimeIndex): subarr = data.values if offset is None: offset = data.offset verify_integrity = False else: if data.dtype != _NS_DTYPE: subarr = lib.cast_to_nanoseconds(data) else: subarr = data elif data.dtype == _INT64_DTYPE: if copy: subarr = np.asarray(data, dtype=_NS_DTYPE) else: subarr = data.view(_NS_DTYPE) else: subarr = tools.to_datetime(data) if not np.issubdtype(subarr.dtype, np.datetime64): raise TypeError("Unable to convert %s to datetime dtype" % str(data)) if tz is not None: tz = tools._maybe_get_tz(tz) # Convert local to UTC ints = subarr.view("i8") subarr = lib.tz_localize_to_utc(ints, tz) subarr = subarr.view(_NS_DTYPE) subarr = subarr.view(cls) subarr.name = name subarr.offset = offset subarr.tz = tz if verify_integrity and len(subarr) > 0: if offset is not None and not freq_infer: inferred = subarr.inferred_freq if inferred != offset.freqstr: raise ValueError("Dates do not conform to passed frequency") if freq_infer: inferred = subarr.inferred_freq if inferred: subarr.offset = to_offset(inferred) return subarr
def __new__( cls, data=None, freq=None, start=None, end=None, periods=None, copy=False, name=None, tz=None, verify_integrity=True, normalize=False, **kwds, ): warn = False if "offset" in kwds and kwds["offset"]: freq = kwds["offset"] warn = True infer_freq = False if not isinstance(freq, DateOffset): if freq != "infer": freq = to_offset(freq) else: infer_freq = True freq = None if warn: import warnings warnings.warn( "parameter 'offset' is deprecated, please use 'freq' instead", FutureWarning ) offset = freq if periods is not None: if com.is_float(periods): periods = int(periods) elif not com.is_integer(periods): raise ValueError("Periods must be a number, got %s" % str(periods)) if data is None and offset is None: raise ValueError("Must provide freq argument if no data is supplied") if data is None: return cls._generate( start, end, periods, name, offset, tz=tz, normalize=normalize ) if not isinstance(data, np.ndarray): if np.isscalar(data): raise ValueError( "DatetimeIndex() must be called with a " "collection of some kind, %s was passed" % repr(data) ) # other iterable of some kind if not isinstance(data, (list, tuple)): data = list(data) data = np.asarray(data, dtype="O") # try a few ways to make it datetime64 if lib.is_string_array(data): data = _str_to_dt_array(data, offset) else: data = tools.to_datetime(data) data.offset = offset if issubclass(data.dtype.type, basestring): subarr = _str_to_dt_array(data, offset) elif issubclass(data.dtype.type, np.datetime64): if isinstance(data, DatetimeIndex): subarr = data.values if offset is None: offset = data.offset verify_integrity = False else: if data.dtype != _NS_DTYPE: subarr = lib.cast_to_nanoseconds(data) else: subarr = data elif data.dtype == _INT64_DTYPE: subarr = np.asarray(data, dtype=_NS_DTYPE) else: subarr = tools.to_datetime(data) if not np.issubdtype(subarr.dtype, np.datetime64): raise TypeError("Unable to convert %s to datetime dtype" % str(data)) if tz is not None: tz = tools._maybe_get_tz(tz) # Convert local to UTC ints = subarr.view("i8") subarr = lib.tz_localize_to_utc(ints, tz) subarr = subarr.view(_NS_DTYPE) subarr = subarr.view(cls) subarr.name = name subarr.offset = offset subarr.tz = tz if verify_integrity and len(subarr) > 0: if offset is not None and not infer_freq: inferred = subarr.inferred_freq if inferred != offset.freqstr: raise ValueError("Dates do not conform to passed frequency") if infer_freq: inferred = subarr.inferred_freq if inferred: subarr.offset = to_offset(inferred) return subarr
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def __repr__(self): from pandas.core.format import _format_datetime64 values = self.values freq = None if self.offset is not None: freq = self.offset.freqstr summary = str(self.__class__) if len(self) == 1: first = _format_datetime64(values[0], tz=self.tz) summary += "\n[%s]" % first elif len(self) == 2: first = _format_datetime64(values[0], tz=self.tz) last = _format_datetime64(values[-1], tz=self.tz) summary += "\n[%s, %s]" % (first, last) elif len(self) > 2: first = _format_datetime64(values[0], tz=self.tz) last = _format_datetime64(values[-1], tz=self.tz) summary += "\n[%s, ..., %s]" % (first, last) tagline = "\nLength: %d, Freq: %s, Timezone: %s" summary += tagline % (len(self), freq, self.tz) return summary
def __repr__(self): from pandas.core.format import _format_datetime64 values = self.values freq = None if self.offset is not None: freq = self.offset.freqstr summary = str(self.__class__) if len(self) > 0: first = _format_datetime64(values[0], tz=self.tz) last = _format_datetime64(values[-1], tz=self.tz) summary += "\n[%s, ..., %s]" % (first, last) tagline = "\nLength: %d, Freq: %s, Timezone: %s" summary += tagline % (len(self), freq, self.tz) return summary
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def intersection(self, other): """ Specialized intersection for DatetimeIndex objects. May be much faster than Index.union Parameters ---------- other : DatetimeIndex or array-like Returns ------- y : Index or DatetimeIndex """ if not isinstance(other, DatetimeIndex): try: other = DatetimeIndex(other) except TypeError: pass result = Index.intersection(self, other) if isinstance(result, DatetimeIndex): if result.freq is None: result.offset = to_offset(result.inferred_freq) return result elif ( other.offset is None or self.offset is None or other.offset != self.offset or (not self.is_monotonic or not other.is_monotonic) ): result = Index.intersection(self, other) if isinstance(result, DatetimeIndex): if result.freq is None: result.offset = to_offset(result.inferred_freq) return result # to make our life easier, "sort" the two ranges if self[0] <= other[0]: left, right = self, other else: left, right = other, self end = min(left[-1], right[-1]) start = right[0] if end < start: return type(self)(data=[]) else: lslice = slice(*left.slice_locs(start, end)) left_chunk = left.values[lslice] return self._view_like(left_chunk)
def intersection(self, other): """ Specialized intersection for DatetimeIndex objects. May be much faster than Index.union Parameters ---------- other : DatetimeIndex or array-like Returns ------- y : Index or DatetimeIndex """ if not isinstance(other, DatetimeIndex): try: other = DatetimeIndex(other) except TypeError: pass result = Index.intersection(self, other) if isinstance(result, DatetimeIndex): if result.freq is None: result.offset = to_offset(result.inferred_freq) return result elif other.offset != self.offset or ( not self.is_monotonic or not other.is_monotonic ): result = Index.intersection(self, other) if isinstance(result, DatetimeIndex): if result.freq is None: result.offset = to_offset(result.inferred_freq) return result # to make our life easier, "sort" the two ranges if self[0] <= other[0]: left, right = self, other else: left, right = other, self end = min(left[-1], right[-1]) start = right[0] if end < start: return type(self)(data=[]) else: lslice = slice(*left.slice_locs(start, end)) left_chunk = left.values[lslice] return self._view_like(left_chunk)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def get_value(self, series, key): """ Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ try: return Index.get_value(self, series, key) except KeyError: try: loc = self._get_string_slice(key) return series[loc] except (TypeError, ValueError, KeyError): pass if isinstance(key, time): locs = self.indexer_at_time(key) return series.take(locs) if isinstance(key, basestring): stamp = Timestamp(key, tz=self.tz) else: stamp = Timestamp(key) try: return self._engine.get_value(series, stamp) except KeyError: raise KeyError(stamp)
def get_value(self, series, key): """ Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ try: return Index.get_value(self, series, key) except KeyError: try: loc = self._get_string_slice(key) return series[loc] except (TypeError, ValueError, KeyError): pass if isinstance(key, time): locs = self.indexer_at_time(key) return series.take(locs) stamp = Timestamp(key) try: return self._engine.get_value(series, stamp) except KeyError: raise KeyError(stamp)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def date_range( start=None, end=None, periods=None, freq="D", tz=None, normalize=False, name=None ): """ Return a fixed frequency datetime index, with day (calendar) as the default frequency Parameters ---------- start : string or datetime-like, default None Left bound for generating dates end : string or datetime-like, default None Right bound for generating dates periods : integer or None, default None If None, must specify start and end freq : string or DateOffset, default 'D' (calendar daily) Frequency strings can have multiples, e.g. '5H' tz : string or None Time zone name for returning localized DatetimeIndex, for example Asia/Beijing normalize : bool, default False Normalize start/end dates to midnight before generating date range name : str, default None Name of the resulting index Notes ----- 2 of start, end, or periods must be specified Returns ------- rng : DatetimeIndex """ return DatetimeIndex( start=start, end=end, periods=periods, freq=freq, tz=tz, normalize=normalize, name=name, )
def date_range(start=None, end=None, periods=None, freq="D", tz=None, normalize=False): """ Return a fixed frequency datetime index, with day (calendar) as the default frequency Parameters ---------- start : string or datetime-like, default None Left bound for generating dates end : string or datetime-like, default None Right bound for generating dates periods : integer or None, default None If None, must specify start and end freq : string or DateOffset, default 'D' (calendar daily) Frequency strings can have multiples, e.g. '5H' tz : string or None Time zone name for returning localized DatetimeIndex, for example Asia/Beijing normalize : bool, default False Normalize start/end dates to midnight before generating date range Notes ----- 2 of start, end, or periods must be specified Returns ------- rng : DatetimeIndex """ return DatetimeIndex( start=start, end=end, periods=periods, freq=freq, tz=tz, normalize=normalize )
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def bdate_range( start=None, end=None, periods=None, freq="B", tz=None, normalize=True, name=None ): """ Return a fixed frequency datetime index, with business day as the default frequency Parameters ---------- start : string or datetime-like, default None Left bound for generating dates end : string or datetime-like, default None Right bound for generating dates periods : integer or None, default None If None, must specify start and end freq : string or DateOffset, default 'B' (business daily) Frequency strings can have multiples, e.g. '5H' tz : string or None Time zone name for returning localized DatetimeIndex, for example Asia/Beijing normalize : bool, default False Normalize start/end dates to midnight before generating date range name : str, default None Name for the resulting index Notes ----- 2 of start, end, or periods must be specified Returns ------- rng : DatetimeIndex """ return DatetimeIndex( start=start, end=end, periods=periods, freq=freq, tz=tz, normalize=normalize, name=name, )
def bdate_range(start=None, end=None, periods=None, freq="B", tz=None, normalize=True): """ Return a fixed frequency datetime index, with business day as the default frequency Parameters ---------- start : string or datetime-like, default None Left bound for generating dates end : string or datetime-like, default None Right bound for generating dates periods : integer or None, default None If None, must specify start and end freq : string or DateOffset, default 'B' (business daily) Frequency strings can have multiples, e.g. '5H' tz : string or None Time zone name for returning localized DatetimeIndex, for example Asia/Beijing normalize : bool, default False Normalize start/end dates to midnight before generating date range Notes ----- 2 of start, end, or periods must be specified Returns ------- rng : DatetimeIndex """ return DatetimeIndex( start=start, end=end, periods=periods, freq=freq, tz=tz, normalize=normalize )
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def apply(self, other): n = self.n wkday, _ = lib.monthrange(other.year, other.month) first = _get_firstbday(wkday) if other.day > first and n <= 0: # as if rolled forward already n += 1 elif other.day < first and n > 0: other = other + timedelta(days=first - other.day) n -= 1 other = other + relativedelta(months=n) wkday, _ = lib.monthrange(other.year, other.month) first = _get_firstbday(wkday) result = datetime(other.year, other.month, first) return result
def apply(self, other): n = self.n wkday, _ = lib.monthrange(other.year, other.month) first = _get_firstbday(wkday) if other.day > first and n <= 0: # as if rolled forward already n += 1 other = other + relativedelta(months=n) wkday, _ = lib.monthrange(other.year, other.month) first = _get_firstbday(wkday) result = datetime(other.year, other.month, first) return result
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _from_arraylike(cls, data, freq): if not isinstance(data, np.ndarray): if np.isscalar(data) or isinstance(data, Period): raise ValueError( "PeriodIndex() must be called with a " "collection of some kind, %s was passed" % repr(data) ) # other iterable of some kind if not isinstance(data, (list, tuple)): data = list(data) try: data = com._ensure_int64(data) if freq is None: raise ValueError("freq not specified") data = np.array( [Period(x, freq=freq).ordinal for x in data], dtype=np.int64 ) except (TypeError, ValueError): data = com._ensure_object(data) if freq is None and len(data) > 0: freq = getattr(data[0], "freq", None) if freq is None: raise ValueError( "freq not specified and cannot be inferred from first element" ) data = _get_ordinals(data, freq) else: if isinstance(data, PeriodIndex): if freq is None or freq == data.freq: freq = data.freq data = data.values else: base1, _ = _gfc(data.freq) base2, _ = _gfc(freq) data = plib.period_asfreq_arr(data.values, base1, base2, 1) else: if freq is None and len(data) > 0: freq = getattr(data[0], "freq", None) if freq is None: raise ValueError( ("freq not specified and cannot be inferred from first element") ) if np.issubdtype(data.dtype, np.datetime64): data = dt64arr_to_periodarr(data, freq) elif data.dtype == np.int64: pass else: try: data = com._ensure_int64(data) except (TypeError, ValueError): data = com._ensure_object(data) data = _get_ordinals(data, freq) return data, freq
def _from_arraylike(cls, data, freq): if not isinstance(data, np.ndarray): if np.isscalar(data) or isinstance(data, Period): raise ValueError( "PeriodIndex() must be called with a " "collection of some kind, %s was passed" % repr(data) ) # other iterable of some kind if not isinstance(data, (list, tuple)): data = list(data) try: data = np.array(data, dtype="i8") except (TypeError, ValueError): data = np.array(data, dtype="O") if freq is None and len(data) > 0: freq = getattr(data[0], "freq", None) if freq is None: raise ValueError( ("freq not specified and cannot be inferred from first element") ) data = _period_unbox_array(data, check=freq) else: if isinstance(data, PeriodIndex): if freq is None or freq == data.freq: freq = data.freq data = data.values else: base1, _ = _gfc(data.freq) base2, _ = _gfc(freq) data = plib.period_asfreq_arr(data.values, base1, base2, 1) else: if freq is None and len(data) > 0: freq = getattr(data[0], "freq", None) if freq is None: raise ValueError( ("freq not specified and cannot be inferred from first element") ) if np.issubdtype(data.dtype, np.datetime64): data = dt64arr_to_periodarr(data, freq) elif data.dtype == np.int64: pass else: try: data = data.astype("i8") except (TypeError, ValueError): data = data.astype("O") data = _period_unbox_array(data, check=freq) return data, freq
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def period_range(start=None, end=None, periods=None, freq="D", name=None): """ Return a fixed frequency datetime index, with day (calendar) as the default frequency Parameters ---------- start : end : periods : int, default None Number of periods in the index freq : str/DateOffset, default 'D' Frequency alias name : str, default None Name for the resulting PeriodIndex Returns ------- prng : PeriodIndex """ return PeriodIndex(start=start, end=end, periods=periods, freq=freq, name=name)
def period_range(start=None, end=None, periods=None, freq="D"): """ Return a fixed frequency datetime index, with day (calendar) as the default frequency Parameters ---------- start : end : normalize : bool, default False Normalize start/end dates to midnight before generating date range Returns ------- """ return PeriodIndex(start=start, end=end, periods=periods, freq=freq)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def tsplot(series, plotf, **kwargs): """ Plots a Series on the given Matplotlib axes or the current axes Parameters ---------- axes : Axes series : Series Notes _____ Supports same kwargs as Axes.plot """ # Used inferred freq is possible, need a test case for inferred if "ax" in kwargs: ax = kwargs.pop("ax") else: import matplotlib.pyplot as plt ax = plt.gca() freq = _get_freq(ax, series) # resample against axes freq if necessary if freq is None: # pragma: no cover raise ValueError("Cannot use dynamic axis without frequency info") else: # Convert DatetimeIndex to PeriodIndex if isinstance(series.index, DatetimeIndex): series = series.to_period(freq=freq) freq, ax_freq, series = _maybe_resample(series, ax, freq, plotf, kwargs) # Set ax with freq info _decorate_axes(ax, freq, kwargs) # mask missing values args = _maybe_mask(series) # how to make sure ax.clear() flows through? if not hasattr(ax, "_plot_data"): ax._plot_data = [] ax._plot_data.append((series, kwargs)) # styles style = kwargs.pop("style", None) if style is not None: args.append(style) lines = plotf(ax, *args, **kwargs) label = kwargs.get("label", None) # set date formatter, locators and rescale limits format_dateaxis(ax, ax.freq) left, right = _get_xlim(ax.get_lines()) ax.set_xlim(left, right) return lines
def tsplot(series, plotf, **kwargs): """ Plots a Series on the given Matplotlib axes or the current axes Parameters ---------- axes : Axes series : Series Notes _____ Supports same kwargs as Axes.plot """ # Used inferred freq is possible, need a test case for inferred if "ax" in kwargs: ax = kwargs.pop("ax") else: import matplotlib.pyplot as plt ax = plt.gca() freq = _get_freq(ax, series) # resample against axes freq if necessary if freq is None: # pragma: no cover raise ValueError("Cannot use dynamic axis without frequency info") else: ax_freq = getattr(ax, "freq", None) if (ax_freq is not None) and (freq != ax_freq): if frequencies.is_subperiod(freq, ax_freq): # downsample how = kwargs.pop("how", "last") series = series.resample(ax_freq, how=how) elif frequencies.is_superperiod(freq, ax_freq): series = series.resample(ax_freq) else: # one freq is weekly how = kwargs.pop("how", "last") series = series.resample("D", how=how, fill_method="pad") series = series.resample(ax_freq, how=how, fill_method="pad") freq = ax_freq # Convert DatetimeIndex to PeriodIndex if isinstance(series.index, DatetimeIndex): series = series.to_period(freq=freq) style = kwargs.pop("style", None) # Specialized ts plotting attributes for Axes ax.freq = freq xaxis = ax.get_xaxis() xaxis.freq = freq ax.legendlabels = [kwargs.get("label", None)] ax.view_interval = None ax.date_axis_info = None # format args and lot args = _maybe_mask(series) if style is not None: args.append(style) plotf(ax, *args, **kwargs) format_dateaxis(ax, ax.freq) left, right = _get_xlim(ax.get_lines()) ax.set_xlim(left, right) return ax
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def initialize_options(self): self.all = True self._clean_me = [] self._clean_trees = [] self._clean_exclude = ["np_datetime.c", "np_datetime_strings.c", "period.c"] for root, dirs, files in list(os.walk("pandas")): for f in files: if f in self._clean_exclude: continue if os.path.splitext(f)[-1] in (".pyc", ".so", ".o", ".pyd", ".c", ".orig"): self._clean_me.append(pjoin(root, f)) for d in dirs: if d == "__pycache__": self._clean_trees.append(pjoin(root, d)) for d in ("build",): if os.path.exists(d): self._clean_trees.append(d)
def initialize_options(self): self.all = True self._clean_me = [] self._clean_trees = [] self._clean_exclude = ["np_datetime.c", "np_datetime_strings.c", "period.c"] for root, dirs, files in list(os.walk("pandas")): for f in files: if f in self._clean_exclude: continue if os.path.splitext(f)[-1] in (".pyc", ".so", ".o", ".pyd", ".c"): self._clean_me.append(pjoin(root, f)) for d in dirs: if d == "__pycache__": self._clean_trees.append(pjoin(root, d)) for d in ("build",): if os.path.exists(d): self._clean_trees.append(d)
https://github.com/pandas-dev/pandas/issues/1628
In [1]: from pandas import * In [2]: a = DataFrame(columns=['column1'], data=[1]) In [3]: b = DataFrame(columns=['column1']) In [4]: a.merge(b, on=['column1'], how='left') IndexError Traceback (most recent call last) IndexError: index out of range for array
IndexError
def _dt_index_cmp(opname): """ Wrap comparison operations to convert datetime-like to datetime64 """ def wrapper(self, other): func = getattr(super(DatetimeIndex, self), opname) if isinstance(other, datetime): func = getattr(self, opname) other = _to_m8(other) elif isinstance(other, list): other = DatetimeIndex(other) elif not isinstance(other, np.ndarray): other = _ensure_datetime64(other) result = func(other) try: return result.view(np.ndarray) except: return result return wrapper
def _dt_index_cmp(opname): """ Wrap comparison operations to convert datetime-like to datetime64 """ def wrapper(self, other): if isinstance(other, datetime): func = getattr(self, opname) result = func(_to_m8(other)) elif isinstance(other, np.ndarray): func = getattr(super(DatetimeIndex, self), opname) result = func(other) else: other = _ensure_datetime64(other) func = getattr(super(DatetimeIndex, self), opname) result = func(other) try: return result.view(np.ndarray) except: return result return wrapper
https://github.com/pandas-dev/pandas/issues/1430
from pandas import * import numpy as np periods = 1000 ind = DatetimeIndex(start='2012/1/1', freq='5min', periods=periods) df = DataFrame({'high': np.arange(periods), 'low': np.arange(periods)}, index=ind) grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day)) In [9]: grouped.groups ValueError Traceback (most recent call last) <ipython-input-9-aec229cf123a> in <module>() ----> 1 grouped.groups ~/pandas/pandas/core/groupby.pyc in groups(self) 150 @property 151 def groups(self): --> 152 return self.grouper.groups 153 154 @property ~/pandas/pandas/core/index.pyc in groupby(self, to_groupby) 740 741 def groupby(self, to_groupby): --> 742 return self._groupby(self.values, to_groupby) 743 744 def map(self, mapper): ... ... ... ~/pandas/pandas/lib.so in pandas.lib.groupby_arrays (pandas/src/tseries.c:67246)() ValueError: Buffer dtype mismatch, expected 'int64_t' but got Python object
ValueError
def wrapper(self, other): func = getattr(super(DatetimeIndex, self), opname) if isinstance(other, datetime): func = getattr(self, opname) other = _to_m8(other) elif isinstance(other, list): other = DatetimeIndex(other) elif not isinstance(other, np.ndarray): other = _ensure_datetime64(other) result = func(other) try: return result.view(np.ndarray) except: return result
def wrapper(self, other): if isinstance(other, datetime): func = getattr(self, opname) result = func(_to_m8(other)) elif isinstance(other, np.ndarray): func = getattr(super(DatetimeIndex, self), opname) result = func(other) else: other = _ensure_datetime64(other) func = getattr(super(DatetimeIndex, self), opname) result = func(other) try: return result.view(np.ndarray) except: return result
https://github.com/pandas-dev/pandas/issues/1430
from pandas import * import numpy as np periods = 1000 ind = DatetimeIndex(start='2012/1/1', freq='5min', periods=periods) df = DataFrame({'high': np.arange(periods), 'low': np.arange(periods)}, index=ind) grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day)) In [9]: grouped.groups ValueError Traceback (most recent call last) <ipython-input-9-aec229cf123a> in <module>() ----> 1 grouped.groups ~/pandas/pandas/core/groupby.pyc in groups(self) 150 @property 151 def groups(self): --> 152 return self.grouper.groups 153 154 @property ~/pandas/pandas/core/index.pyc in groupby(self, to_groupby) 740 741 def groupby(self, to_groupby): --> 742 return self._groupby(self.values, to_groupby) 743 744 def map(self, mapper): ... ... ... ~/pandas/pandas/lib.so in pandas.lib.groupby_arrays (pandas/src/tseries.c:67246)() ValueError: Buffer dtype mismatch, expected 'int64_t' but got Python object
ValueError
def tsplot(series, plotf, *args, **kwargs): """ Plots a Series on the given Matplotlib axes object Parameters ---------- axes : Axes series : Series Notes _____ Supports same args and kwargs as Axes.plot """ # Used inferred freq is possible, need a test case for inferred freq = getattr(series.index, "freq", None) if freq is None and hasattr(series.index, "inferred_freq"): freq = series.index.inferred_freq if isinstance(freq, DateOffset): freq = freq.rule_code else: freq = frequencies.get_base_alias(freq) freq = frequencies.to_calendar_freq(freq) # Convert DatetimeIndex to PeriodIndex if isinstance(series.index, DatetimeIndex): idx = series.index.to_period(freq=freq) series = Series(series.values, idx, name=series.name) if not isinstance(series.index, PeriodIndex): # try to get it to DatetimeIndex then to period if series.index.inferred_type == "datetime": idx = DatetimeIndex(series.index).to_period(freq=freq) series = Series(series.values, idx, name=series.name) else: raise TypeError( "series argument to tsplot must have DatetimeIndex or PeriodIndex" ) if freq != series.index.freq: series = series.asfreq(freq) series = series.dropna() if "ax" in kwargs: ax = kwargs.pop("ax") else: ax = plt.gca() # Specialized ts plotting attributes for Axes ax.freq = freq xaxis = ax.get_xaxis() xaxis.freq = freq xaxis.converter = DateConverter ax.legendlabels = [kwargs.get("label", None)] ax.view_interval = None ax.date_axis_info = None # format args and lot args = _check_plot_params(series, series.index, freq, *args) plotted = plotf(ax, *args, **kwargs) format_dateaxis(ax, ax.freq) # when adding a right axis (using add_yaxis), for some reason the # x axis limits don't get properly set. This gets around the problem xlim = ax.get_xlim() if xlim[0] == 0.0 and xlim[1] == 1.0: # if xlim still at default values, autoscale the axis ax.autoscale_view() left = series.index[0] # get_datevalue(series.index[0], freq) right = series.index[-1] # get_datevalue(series.index[-1], freq) ax.set_xlim(left, right) return plotted
def tsplot(series, plotf, *args, **kwargs): """ Plots a Series on the given Matplotlib axes object Parameters ---------- axes : Axes series : Series Notes _____ Supports same args and kwargs as Axes.plot """ # Used inferred freq is possible, need a test case for inferred freq = getattr(series.index, "freq", None) if freq is None and hasattr(series.index, "inferred_freq"): freq = series.index.inferred_freq if isinstance(freq, DateOffset): freq = freq.rule_code freq = frequencies.to_calendar_freq(freq) # Convert DatetimeIndex to PeriodIndex if isinstance(series.index, DatetimeIndex): idx = series.index.to_period(freq=freq) series = Series(series.values, idx, name=series.name) if not isinstance(series.index, PeriodIndex): # try to get it to DatetimeIndex then to period if series.index.inferred_type == "datetime": idx = DatetimeIndex(series.index).to_period(freq=freq) series = Series(series.values, idx, name=series.name) else: raise TypeError( "series argument to tsplot must have DatetimeIndex or PeriodIndex" ) if freq != series.index.freq: series = series.asfreq(freq) series = series.dropna() if "ax" in kwargs: ax = kwargs.pop("ax") else: ax = plt.gca() # Specialized ts plotting attributes for Axes ax.freq = freq xaxis = ax.get_xaxis() xaxis.freq = freq xaxis.converter = DateConverter ax.legendlabels = [kwargs.get("label", None)] ax.view_interval = None ax.date_axis_info = None # format args and lot args = _check_plot_params(series, series.index, freq, *args) plotted = plotf(ax, *args, **kwargs) format_dateaxis(ax, ax.freq) # when adding a right axis (using add_yaxis), for some reason the # x axis limits don't get properly set. This gets around the problem xlim = ax.get_xlim() if xlim[0] == 0.0 and xlim[1] == 1.0: # if xlim still at default values, autoscale the axis ax.autoscale_view() left = series.index[0] # get_datevalue(series.index[0], freq) right = series.index[-1] # get_datevalue(series.index[-1], freq) ax.set_xlim(left, right) return plotted
https://github.com/pandas-dev/pandas/issues/1357
In [4]: ts.plot() Out[4]: <matplotlib.axes.AxesSubplot at 0x41cc310> In [5]: ts.index.fr ts.index.freq ts.index.freqstr In [5]: ts.index.freq Out[5]: <10 Days> In [6]: ts.index.freq = None --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /home/wesm/Dropbox/book/svn/<ipython-input-6-d89557d7f8e5> in <module>() ----> 1 ts.index.freq = None AttributeError: can't set attribute In [7]: ts.index.offset = None In [8]: ts Out[8]: 2000-01-01 2.963378 2000-01-11 -0.685998 2000-01-21 0.392812 2000-01-31 -0.143893 2000-02-10 -1.162283 2000-02-20 -0.460511 2000-03-01 -0.751741 2000-03-11 -0.567428 2000-03-21 -0.439105 2000-03-31 0.040322 2000-04-10 -0.929786 2000-04-20 -0.620005 2000-04-30 0.482502 2000-05-10 0.109013 2000-05-20 0.657817 2000-05-30 -0.668386 2000-06-09 -1.797074 2000-06-19 -0.197738 2000-06-29 -0.312481 2000-07-09 1.240477 2000-07-19 0.447583 2000-07-29 0.188429 2000-08-08 -0.117540 2000-08-18 -1.145495 2000-08-28 0.479124 2000-09-07 0.309968 2000-09-17 0.769928 2000-09-27 -0.501629 2000-10-07 0.164322 2000-10-17 -0.554113 2000-10-27 0.468588 2000-11-06 0.857458 2000-11-16 0.508256 2000-11-26 -0.452384 2000-12-06 1.732538 2000-12-16 0.695495 2000-12-26 0.441233 2001-01-05 -0.271561 In [9]: ts.index.offset = None In [10]: ts.plot() --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/wesm/Dropbox/book/svn/<ipython-input-10-132f3667ee95> in <module>() ----> 1 ts.plot() /home/wesm/code/pandas/pandas/tools/plotting.pyc in plot_series(series, label, kind, use_index, rot, xticks, yticks, xlim, ylim, ax, style, grid, logy, **kwds) 758 legend=False, grid=grid, label=label, **kwds) 759 --> 760 plot_obj.generate() 761 plot_obj.draw() 762 /home/wesm/code/pandas/pandas/tools/plotting.pyc in generate(self) 239 self._compute_plot_data() 240 self._setup_subplots() --> 241 self._make_plot() 242 self._post_plot_logic() 243 self._adorn_subplots() /home/wesm/code/pandas/pandas/tools/plotting.pyc in _make_plot(self) 426 if self.use_index and self.has_ts_index: 427 data = self._maybe_convert_index(self.data) --> 428 self._make_ts_plot(data) 429 else: 430 x = self._get_xticks() /home/wesm/code/pandas/pandas/tools/plotting.pyc in _make_ts_plot(self, data, **kwargs) 478 479 label = com._stringify(self.label) --> 480 tsplot(data, plotf, ax=ax, label=label, **kwargs) 481 ax.grid(self.grid) 482 else: /home/wesm/code/pandas/pandas/tseries/plotting.pyc in tsplot(series, plotf, *args, **kwargs) 114 # format args and lot 115 args = _check_plot_params(series, series.index, freq, *args) --> 116 plotted = plotf(ax, *args, **kwargs) 117 118 format_dateaxis(ax, ax.freq) /home/wesm/code/repos/matplotlib/lib/matplotlib/axes.pyc in plot(self, *args, **kwargs) 3892 lines = [] 3893 -> 3894 for line in self._get_lines(*args, **kwargs): 3895 self.add_line(line) 3896 lines.append(line) /home/wesm/code/repos/matplotlib/lib/matplotlib/axes.pyc in _grab_next_args(self, *args, **kwargs) 321 return 322 if len(remaining) <= 3: --> 323 for seg in self._plot_args(remaining, kwargs): 324 yield seg 325 return /home/wesm/code/repos/matplotlib/lib/matplotlib/axes.pyc in _plot_args(self, tup, kwargs) 299 x = np.arange(y.shape[0], dtype=float) 300 --> 301 x, y = self._xy_from_xy(x, y) 302 303 if self.command == 'plot': /home/wesm/code/repos/matplotlib/lib/matplotlib/axes.pyc in _xy_from_xy(self, x, y) 215 def _xy_from_xy(self, x, y): 216 if self.axes.xaxis is not None and self.axes.yaxis is not None: --> 217 bx = self.axes.xaxis.update_units(x) 218 by = self.axes.yaxis.update_units(y) 219 /home/wesm/code/repos/matplotlib/lib/matplotlib/axis.pyc in update_units(self, data) 1276 """ 1277 -> 1278 converter = munits.registry.get_converter(data) 1279 if converter is None: 1280 return False /home/wesm/code/repos/matplotlib/lib/matplotlib/units.pyc in get_converter(self, x) 131 132 if converter is None and iterable(x): --> 133 for thisx in x: 134 # Make sure that recursing might actually lead to a solution, if 135 # we are just going to re-examine another item of the same kind, /home/wesm/code/pandas/pandas/tseries/period.pyc in __iter__(self) 685 def __iter__(self): 686 for val in self.values: --> 687 yield Period(ordinal=val, freq=self.freq) 688 689 @property /home/wesm/code/pandas/pandas/tseries/period.pyc in __init__(self, value, freq, ordinal, year, month, quarter, day, hour, minute, second) 136 base, mult = _gfc(freq) 137 if mult != 1: --> 138 raise ValueError('Only mult == 1 supported') 139 140 if self.ordinal is None: ValueError: Only mult == 1 supported
AttributeError
def get_loc(self, key): """ Get integer location for requested label Returns ------- loc : int """ try: return self._engine.get_loc(key) except KeyError: try: return self._get_string_slice(key) except (TypeError, KeyError): pass if isinstance(key, time): return self._indices_at_time(key) stamp = Timestamp(key) try: return self._engine.get_loc(stamp) except KeyError: raise KeyError(stamp)
def get_loc(self, key): """y Get integer location for requested label Returns ------- loc : int """ try: return self._engine.get_loc(key) except KeyError: try: return self._get_string_slice(key) except (TypeError, KeyError): pass if isinstance(key, time): return self._indices_at_time(key) stamp = Timestamp(key) try: return self._engine.get_loc(stamp) except KeyError: raise KeyError(stamp)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def match(to_match, values, na_sentinel=-1): """ Compute locations of to_match into values Parameters ---------- to_match : array-like values to find positions of values : array-like Unique set of values na_sentinel : int, default -1 Value to mark "not found" Examples -------- Returns ------- match : ndarray of integers """ values = np.asarray(values) if issubclass(values.dtype.type, basestring): values = np.array(values, dtype="O") f = lambda htype, caster: _match_generic(to_match, values, htype, caster) return _hashtable_algo(f, values.dtype)
def match(values, index): """ Parameters ---------- Returns ------- match : ndarray """ if com.is_float_dtype(index): return _match_generic(values, index, lib.Float64HashTable, com._ensure_float64) elif com.is_integer_dtype(index): return _match_generic(values, index, lib.Int64HashTable, com._ensure_int64) else: return _match_generic(values, index, lib.PyObjectHashTable, com._ensure_object)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def unique(values): """ Compute unique values (not necessarily sorted) efficiently from input array of values Parameters ---------- values : array-like Returns ------- uniques """ f = lambda htype, caster: _unique_generic(values, htype, caster) return _hashtable_algo(f, values.dtype)
def unique(values): """ """ pass
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def count(values, uniques=None): f = lambda htype, caster: _count_generic(values, htype, caster) if uniques is not None: raise NotImplementedError else: return _hashtable_algo(f, values.dtype)
def count(values, uniques=None): if uniques is not None: raise NotImplementedError else: if com.is_float_dtype(values): return _count_generic(values, lib.Float64HashTable, com._ensure_float64) elif com.is_integer_dtype(values): return _count_generic(values, lib.Int64HashTable, com._ensure_int64) else: return _count_generic(values, lib.PyObjectHashTable, com._ensure_object)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _count_generic(values, table_type, type_caster): from pandas.core.series import Series values = type_caster(values) table = table_type(len(values)) uniques, labels, counts = table.factorize(values) return Series(counts, index=uniques)
def _count_generic(values, table_type, type_caster): values = type_caster(values) table = table_type(len(values)) uniques, labels, counts = table.factorize(values) return Series(counts, index=uniques)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def factorize(values, sort=False, order=None, na_sentinel=-1): """ Encode input values as an enumerated type or categorical variable Parameters ---------- values : sequence sort : order : Returns ------- """ values = np.asarray(values) is_datetime = com.is_datetime64_dtype(values) hash_klass, values = _get_data_algo(values, _hashtables) uniques = [] table = hash_klass(len(values)) labels, counts = table.get_labels(values, uniques, 0, na_sentinel) labels = com._ensure_platform_int(labels) uniques = com._asarray_tuplesafe(uniques) if sort and len(counts) > 0: sorter = uniques.argsort() reverse_indexer = np.empty(len(sorter), dtype=np.int_) reverse_indexer.put(sorter, np.arange(len(sorter))) mask = labels < 0 labels = reverse_indexer.take(labels) np.putmask(labels, mask, -1) uniques = uniques.take(sorter) counts = counts.take(sorter) if is_datetime: uniques = np.array(uniques, dtype="M8[ns]") return labels, uniques, counts
def factorize(values, sort=False, order=None, na_sentinel=-1): """ Encode input values as an enumerated type or categorical variable Parameters ---------- values : sequence sort : order : Returns ------- """ hash_klass, values = _get_data_algo(values, _hashtables) uniques = [] table = hash_klass(len(values)) labels, counts = table.get_labels(values, uniques, 0, na_sentinel) uniques = com._asarray_tuplesafe(uniques) if sort and len(counts) > 0: sorter = uniques.argsort() reverse_indexer = np.empty(len(sorter), dtype=np.int32) reverse_indexer.put(sorter, np.arange(len(sorter))) mask = labels < 0 labels = reverse_indexer.take(labels) np.putmask(labels, mask, -1) uniques = uniques.take(sorter) counts = counts.take(sorter) return labels, uniques, counts
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def value_counts(values, sort=True, ascending=False): """ Compute a histogram of the counts of non-null values Returns ------- value_counts : Series """ from pandas.core.series import Series from collections import defaultdict if com.is_integer_dtype(values.dtype): values = com._ensure_int64(values) keys, counts = lib.value_count_int64(values) result = Series(counts, index=keys) else: counter = defaultdict(lambda: 0) values = values[com.notnull(values)] for value in values: counter[value] += 1 result = Series(counter) if sort: result.sort() if not ascending: result = result[::-1] return result
def value_counts(values, sort=True, ascending=False): """ Compute a histogram of the counts of non-null values Returns ------- value_counts : Series """ from collections import defaultdict if com.is_integer_dtype(values.dtype): values = com._ensure_int64(values) keys, counts = lib.value_count_int64(values) result = Series(counts, index=keys) else: counter = defaultdict(lambda: 0) values = values[com.notnull(values)] for value in values: counter[value] += 1 result = Series(counter) if sort: result.sort() if not ascending: result = result[::-1] return result
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _get_data_algo(values, func_map): if com.is_float_dtype(values): f = func_map["float64"] values = com._ensure_float64(values) elif com.is_datetime64_dtype(values): f = func_map["int64"] values = values.view("i8") elif com.is_integer_dtype(values): f = func_map["int64"] values = com._ensure_int64(values) else: f = func_map["generic"] values = com._ensure_object(values) return f, values
def _get_data_algo(values, func_map): if com.is_float_dtype(values): f = func_map["float64"] values = com._ensure_float64(values) elif com.is_integer_dtype(values): f = func_map["int64"] values = com._ensure_int64(values) else: f = func_map["generic"] values = com._ensure_object(values) return f, values
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def isnull(obj): """ Replacement for numpy.isnan / -numpy.isfinite which is suitable for use on object arrays. Parameters ---------- arr: ndarray or object value Returns ------- boolean ndarray or boolean """ if lib.isscalar(obj): return lib.checknull(obj) from pandas.core.generic import PandasObject from pandas import Series if isinstance(obj, np.ndarray): if obj.dtype.kind in ("O", "S"): # Working around NumPy ticket 1542 shape = obj.shape result = np.empty(shape, dtype=bool) vec = lib.isnullobj(obj.ravel()) result[:] = vec.reshape(shape) if isinstance(obj, Series): result = Series(result, index=obj.index, copy=False) elif obj.dtype == np.dtype("M8[ns]"): # this is the NaT pattern result = np.array(obj).view("i8") == lib.iNaT else: result = -np.isfinite(obj) return result elif isinstance(obj, PandasObject): # TODO: optimize for DataFrame, etc. return obj.apply(isnull) else: return obj is None
def isnull(obj): """ Replacement for numpy.isnan / -numpy.isfinite which is suitable for use on object arrays. Parameters ---------- arr: ndarray or object value Returns ------- boolean ndarray or boolean """ if np.isscalar(obj) or obj is None: return lib.checknull(obj) from pandas.core.generic import PandasObject from pandas import Series if isinstance(obj, np.ndarray): if obj.dtype.kind in ("O", "S"): # Working around NumPy ticket 1542 shape = obj.shape result = np.empty(shape, dtype=bool) vec = lib.isnullobj(obj.ravel()) result[:] = vec.reshape(shape) if isinstance(obj, Series): result = Series(result, index=obj.index, copy=False) else: result = -np.isfinite(obj) return result elif isinstance(obj, PandasObject): # TODO: optimize for DataFrame, etc. return obj.apply(isnull) else: return obj is None
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _get_take2d_function(dtype_str, axis=0): if axis == 0: return _take2d_axis0_dict[dtype_str] elif axis == 1: return _take2d_axis1_dict[dtype_str] elif axis == "multi": return _take2d_multi_dict[dtype_str] else: # pragma: no cover raise ValueError("bad axis: %s" % axis)
def _get_take2d_function(dtype_str, axis=0): if axis == 0: return _take2d_axis0_dict[dtype_str] else: return _take2d_axis1_dict[dtype_str]
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def take_1d(arr, indexer, out=None, fill_value=np.nan): """ Specialized Cython take which sets NaN values in one pass """ dtype_str = arr.dtype.name n = len(indexer) indexer = _ensure_int64(indexer) out_passed = out is not None take_f = _take1d_dict.get(dtype_str) if dtype_str in ("int32", "int64", "bool"): try: if out is None: out = np.empty(n, dtype=arr.dtype) take_f(arr, _ensure_int64(indexer), out=out, fill_value=fill_value) except ValueError: mask = indexer == -1 if len(arr) == 0: if not out_passed: out = np.empty(n, dtype=arr.dtype) else: out = ndtake(arr, indexer, out=out) if mask.any(): if out_passed: raise Exception("out with dtype %s does not support NA" % out.dtype) out = _maybe_upcast(out) np.putmask(out, mask, fill_value) elif dtype_str in ("float64", "object", "datetime64[ns]"): if out is None: out = np.empty(n, dtype=arr.dtype) take_f(arr, _ensure_int64(indexer), out=out, fill_value=fill_value) else: out = ndtake(arr, indexer, out=out) mask = indexer == -1 if mask.any(): if out_passed: raise Exception("out with dtype %s does not support NA" % out.dtype) out = _maybe_upcast(out) np.putmask(out, mask, fill_value) return out
def take_1d(arr, indexer, out=None, fill_value=np.nan): """ Specialized Cython take which sets NaN values in one pass """ dtype_str = arr.dtype.name n = len(indexer) if not isinstance(indexer, np.ndarray): # Cython methods expects 32-bit integers indexer = np.array(indexer, dtype=np.int32) out_passed = out is not None if dtype_str in ("int32", "int64", "bool"): try: if out is None: out = np.empty(n, dtype=arr.dtype) take_f = _take1d_dict[dtype_str] take_f(arr, indexer, out=out, fill_value=fill_value) except ValueError: mask = indexer == -1 if len(arr) == 0: if not out_passed: out = np.empty(n, dtype=arr.dtype) else: out = arr.take(indexer, out=out) if mask.any(): if out_passed: raise Exception("out with dtype %s does not support NA" % out.dtype) out = _maybe_upcast(out) np.putmask(out, mask, fill_value) elif dtype_str in ("float64", "object"): if out is None: out = np.empty(n, dtype=arr.dtype) take_f = _take1d_dict[dtype_str] take_f(arr, indexer, out=out, fill_value=fill_value) else: out = arr.take(indexer, out=out) mask = indexer == -1 if mask.any(): if out_passed: raise Exception("out with dtype %s does not support NA" % out.dtype) out = _maybe_upcast(out) np.putmask(out, mask, fill_value) return out
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def take_2d( arr, indexer, out=None, mask=None, needs_masking=None, axis=0, fill_value=np.nan ): """ Specialized Cython take which sets NaN values in one pass """ dtype_str = arr.dtype.name out_shape = list(arr.shape) out_shape[axis] = len(indexer) out_shape = tuple(out_shape) if not isinstance(indexer, np.ndarray): indexer = np.array(indexer, dtype=np.int64) if dtype_str in ("int32", "int64", "bool"): if mask is None: mask = indexer == -1 needs_masking = mask.any() if needs_masking: # upcasting may be required result = ndtake(arr, indexer, axis=axis, out=out) result = _maybe_mask( result, mask, needs_masking, axis=axis, out_passed=out is not None, fill_value=fill_value, ) return result else: if out is None: out = np.empty(out_shape, dtype=arr.dtype) take_f = _get_take2d_function(dtype_str, axis=axis) take_f(arr, _ensure_int64(indexer), out=out, fill_value=fill_value) return out elif dtype_str in ("float64", "object", "datetime64[ns]"): if out is None: out = np.empty(out_shape, dtype=arr.dtype) take_f = _get_take2d_function(dtype_str, axis=axis) take_f(arr, _ensure_int64(indexer), out=out, fill_value=fill_value) return out else: if mask is None: mask = indexer == -1 needs_masking = mask.any() # GH #486 if out is not None and arr.dtype != out.dtype: arr = arr.astype(out.dtype) result = ndtake(arr, indexer, axis=axis, out=out) result = _maybe_mask( result, mask, needs_masking, axis=axis, out_passed=out is not None, fill_value=fill_value, ) return result
def take_2d( arr, indexer, out=None, mask=None, needs_masking=None, axis=0, fill_value=np.nan ): """ Specialized Cython take which sets NaN values in one pass """ dtype_str = arr.dtype.name out_shape = list(arr.shape) out_shape[axis] = len(indexer) out_shape = tuple(out_shape) if not isinstance(indexer, np.ndarray): # Cython methods expects 32-bit integers indexer = np.array(indexer, dtype=np.int32) if dtype_str in ("int32", "int64", "bool"): if mask is None: mask = indexer == -1 needs_masking = mask.any() if needs_masking: # upcasting may be required result = arr.take(indexer, axis=axis, out=out) result = _maybe_mask( result, mask, needs_masking, axis=axis, out_passed=out is not None, fill_value=fill_value, ) return result else: if out is None: out = np.empty(out_shape, dtype=arr.dtype) take_f = _get_take2d_function(dtype_str, axis=axis) take_f(arr, indexer, out=out, fill_value=fill_value) return out elif dtype_str in ("float64", "object"): if out is None: out = np.empty(out_shape, dtype=arr.dtype) take_f = _get_take2d_function(dtype_str, axis=axis) take_f(arr, indexer, out=out, fill_value=fill_value) return out else: if mask is None: mask = indexer == -1 needs_masking = mask.any() # GH #486 if out is not None and arr.dtype != out.dtype: arr = arr.astype(out.dtype) result = arr.take(indexer, axis=axis, out=out) result = _maybe_mask( result, mask, needs_masking, axis=axis, out_passed=out is not None, fill_value=fill_value, ) return result
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def take_fast(arr, indexer, mask, needs_masking, axis=0, out=None, fill_value=np.nan): if arr.ndim == 2: return take_2d( arr, indexer, out=out, mask=mask, needs_masking=needs_masking, axis=axis, fill_value=fill_value, ) indexer = _ensure_platform_int(indexer) result = ndtake(arr, indexer, axis=axis, out=out) result = _maybe_mask( result, mask, needs_masking, axis=axis, out_passed=out is not None, fill_value=fill_value, ) return result
def take_fast(arr, indexer, mask, needs_masking, axis=0, out=None, fill_value=np.nan): if arr.ndim == 2: return take_2d( arr, indexer, out=out, mask=mask, needs_masking=needs_masking, axis=axis, fill_value=fill_value, ) result = arr.take(indexer, axis=axis, out=out) result = _maybe_mask( result, mask, needs_masking, axis=axis, out_passed=out is not None, fill_value=fill_value, ) return result
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def iterpairs(seq): """ Parameters ---------- seq: sequence Returns ------- iterator returning overlapping pairs of elements Example ------- >>> iterpairs([1, 2, 3, 4]) [(1, 2), (2, 3), (3, 4) """ # input may not be sliceable seq_it = iter(seq) seq_it_next = iter(seq) _ = next(seq_it_next) return itertools.izip(seq_it, seq_it_next)
def iterpairs(seq): """ Parameters ---------- seq: sequence Returns ------- iterator returning overlapping pairs of elements Example ------- >>> iterpairs([1, 2, 3, 4]) [(1, 2), (2, 3), (3, 4) """ # input may not be sliceable seq_it = iter(seq) seq_it_next = iter(seq) _ = seq_it_next.next() return itertools.izip(seq_it, seq_it_next)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def is_integer_dtype(arr_or_dtype): if isinstance(arr_or_dtype, np.dtype): tipo = arr_or_dtype.type else: tipo = arr_or_dtype.dtype.type return issubclass(tipo, np.integer) and not issubclass(tipo, np.datetime64)
def is_integer_dtype(arr_or_dtype): if isinstance(arr_or_dtype, np.dtype): tipo = arr_or_dtype.type else: tipo = arr_or_dtype.dtype.type return issubclass(tipo, np.integer)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _astype_nansafe(arr, dtype): if isinstance(dtype, basestring): dtype = np.dtype(dtype) if issubclass(arr.dtype.type, np.datetime64): if dtype == object: return lib.ints_to_pydatetime(arr.view(np.int64)) elif np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer): if np.isnan(arr).any(): raise ValueError("Cannot convert NA to integer") return arr.astype(dtype)
def _astype_nansafe(arr, dtype): if np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer): if np.isnan(arr).any(): raise ValueError("Cannot convert NA to integer") return arr.astype(dtype)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def __new__( cls, start=None, end=None, periods=None, offset=datetools.bday, time_rule=None, tzinfo=None, name=None, **kwds, ): import warnings warnings.warn("DateRange is deprecated, use DatetimeIndex instead", FutureWarning) if time_rule is None: time_rule = kwds.get("timeRule") if time_rule is not None: offset = datetools.get_offset(time_rule) return DatetimeIndex( start=start, end=end, periods=periods, freq=offset, tzinfo=tzinfo, name=name, **kwds, )
def __new__( cls, start=None, end=None, periods=None, offset=datetools.bday, time_rule=None, tzinfo=None, name=None, **kwds, ): time_rule = kwds.get("timeRule", time_rule) if time_rule is not None: offset = datetools.getOffset(time_rule) if time_rule is None: if offset in datetools._offsetNames: time_rule = datetools._offsetNames[offset] # Cachable if not start: start = kwds.get("begin") if not periods: periods = kwds.get("nPeriods") start = datetools.to_datetime(start) end = datetools.to_datetime(end) if start is not None and not isinstance(start, datetime): raise ValueError("Failed to convert %s to datetime" % start) if end is not None and not isinstance(end, datetime): raise ValueError("Failed to convert %s to datetime" % end) # inside cache range. Handle UTC case useCache = _will_use_cache(offset) start, end, tzinfo = _figure_out_timezone(start, end, tzinfo) useCache = useCache and _naive_in_cache_range(start, end) if useCache: index = cls._cached_range( start, end, periods=periods, offset=offset, time_rule=time_rule, name=name ) if tzinfo is None: return index else: xdr = generate_range( start=start, end=end, periods=periods, offset=offset, time_rule=time_rule ) index = list(xdr) if tzinfo is not None: index = [d.replace(tzinfo=tzinfo) for d in index] index = np.array(index, dtype=object, copy=False) index = index.view(cls) index.name = name index.offset = offset index.tzinfo = tzinfo return index
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _expand_axes(self, key): new_axes = [] for k, ax in zip(key, self.axes): if k not in ax: if type(k) != ax.dtype.type: ax = ax.astype("O") new_axes.append(ax.insert(len(ax), k)) else: new_axes.append(ax) return new_axes
def _expand_axes(self, key): new_axes = [] for k, ax in zip(key, self.axes): if k not in ax: new_axes.append(ax.insert(len(ax), k)) else: new_axes.append(ax) return new_axes
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def truncate(self, before=None, after=None, copy=True): """Function truncate a sorted DataFrame / Series before and/or after some particular dates. Parameters ---------- before : date Truncate before date after : date Truncate after date Returns ------- truncated : type of caller """ from pandas.tseries.tools import to_datetime before = to_datetime(before) after = to_datetime(after) if before is not None and after is not None: assert before <= after result = self.ix[before:after] if isinstance(self.index, MultiIndex): result.index = self.index.truncate(before, after) if copy: result = result.copy() return result
def truncate(self, before=None, after=None, copy=True): """Function truncate a sorted DataFrame / Series before and/or after some particular dates. Parameters ---------- before : date Truncate before date after : date Truncate after date Returns ------- truncated : type of caller """ before = datetools.to_datetime(before) after = datetools.to_datetime(after) if before is not None and after is not None: assert before <= after result = self.ix[before:after] if isinstance(self.index, MultiIndex): result.index = self.index.truncate(before, after) if copy: result = result.copy() return result
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def save(self, path): com.save(self, path)
def save(self, path): save(self, path)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def load(cls, path): return com.load(path)
def load(cls, path): return load(path)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def __getitem__(self, key): if type(key) is tuple: try: return self.obj.get_value(*key) except Exception: pass return self._getitem_tuple(key) else: return self._getitem_axis(key, axis=0)
def __getitem__(self, key): if isinstance(key, tuple): try: return self.obj.get_value(*key) except Exception: pass return self._getitem_tuple(key) else: return self._getitem_axis(key, axis=0)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _setitem_with_indexer(self, indexer, value): # also has the side effect of consolidating in-place if self.obj._is_mixed_type: if not isinstance(indexer, tuple): indexer = self._tuplify(indexer) het_axis = self.obj._het_axis het_idx = indexer[het_axis] if isinstance(het_idx, (int, long)): het_idx = [het_idx] plane_indexer = indexer[:het_axis] + indexer[het_axis + 1 :] item_labels = self.obj._get_axis(het_axis) for item in item_labels[het_idx]: data = self.obj[item] data.values[plane_indexer] = value else: if isinstance(indexer, tuple): indexer = _maybe_convert_ix(*indexer) self.obj.values[indexer] = value
def _setitem_with_indexer(self, indexer, value): # also has the side effect of consolidating in-place if self.obj._is_mixed_type: if not isinstance(indexer, tuple): indexer = self._tuplify(indexer) het_axis = self.obj._het_axis het_idx = indexer[het_axis] if isinstance(het_idx, (int, long)): het_idx = [het_idx] if not np.isscalar(value): raise IndexingError( "setting on mixed-type frames only allowed with scalar values" ) plane_indexer = indexer[:het_axis] + indexer[het_axis + 1 :] item_labels = self.obj._get_axis(het_axis) for item in item_labels[het_idx]: data = self.obj[item] data.values[plane_indexer] = value else: if isinstance(indexer, tuple): indexer = _maybe_convert_ix(*indexer) self.obj.values[indexer] = value
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _getitem_tuple(self, tup): try: return self._getitem_lowerdim(tup) except IndexingError: pass # ugly hack for GH #836 if self._multi_take_opportunity(tup): return self._multi_take(tup) # no shortcut needed retval = self.obj for i, key in enumerate(tup): if i >= self.obj.ndim: raise IndexingError("Too many indexers") if _is_null_slice(key): continue retval = retval.ix._getitem_axis(key, axis=i) return retval
def _getitem_tuple(self, tup): try: return self._getitem_lowerdim(tup) except IndexingError: pass # no shortcut needed retval = self.obj for i, key in enumerate(tup): if i >= self.obj.ndim: raise IndexingError("Too many indexers") if _is_null_slice(key): continue retval = retval.ix._getitem_axis(key, axis=i) return retval
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _getitem_lowerdim(self, tup): from pandas.core.frame import DataFrame ax0 = self.obj._get_axis(0) # a bit kludgy if isinstance(ax0, MultiIndex): try: return self._get_label(tup, axis=0) except TypeError: # slices are unhashable pass except Exception: if isinstance(tup[0], slice): raise IndexingError if tup[0] not in ax0: # and tup[0] not in ax0.levels[0]: raise # to avoid wasted computation # df.ix[d1:d2, 0] -> columns first (True) # df.ix[0, ['C', 'B', A']] -> rows first (False) for i, key in enumerate(tup): if _is_label_like(key) or isinstance(key, tuple): section = self._getitem_axis(key, axis=i) # might have been a MultiIndex if section.ndim == self.ndim: new_key = tup[:i] + (_NS,) + tup[i + 1 :] # new_key = tup[:i] + tup[i+1:] else: new_key = tup[:i] + tup[i + 1 :] # unfortunately need an odious kludge here because of # DataFrame transposing convention if isinstance(section, DataFrame) and i > 0 and len(new_key) == 2: a, b = new_key new_key = b, a if len(new_key) == 1: (new_key,) = new_key return section.ix[new_key] raise IndexingError("not applicable")
def _getitem_lowerdim(self, tup): from pandas.core.frame import DataFrame ax0 = self.obj._get_axis(0) # a bit kludgy if isinstance(ax0, MultiIndex): try: return self._get_label(tup, axis=0) except TypeError: # slices are unhashable pass except Exception: if isinstance(tup[0], slice): raise IndexingError if tup[0] not in ax0: raise # to avoid wasted computation # df.ix[d1:d2, 0] -> columns first (True) # df.ix[0, ['C', 'B', A']] -> rows first (False) for i, key in enumerate(tup): if _is_label_like(key) or isinstance(key, tuple): section = self._getitem_axis(key, axis=i) # might have been a MultiIndex if section.ndim == self.ndim: new_key = tup[:i] + (_NS,) + tup[i + 1 :] # new_key = tup[:i] + tup[i+1:] else: new_key = tup[:i] + tup[i + 1 :] # unfortunately need an odious kludge here because of # DataFrame transposing convention if isinstance(section, DataFrame) and i > 0 and len(new_key) == 2: a, b = new_key new_key = b, a if len(new_key) == 1: (new_key,) = new_key return section.ix[new_key] raise IndexingError("not applicable")
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _getitem_iterable(self, key, axis=0): labels = self.obj._get_axis(axis) def _reindex(keys, level=None): try: return self.obj.reindex_axis(keys, axis=axis, level=level) except AttributeError: # Series assert axis == 0 return self.obj.reindex(keys, level=level) if com._is_bool_indexer(key): key = _check_bool_indexer(labels, key) return _reindex(labels[np.asarray(key)]) else: if isinstance(key, Index): # want Index objects to pass through untouched keyarr = key else: # asarray can be unsafe, NumPy strings are weird keyarr = _asarray_tuplesafe(key) if _is_integer_dtype(keyarr) and not _is_integer_index(labels): return self.obj.take(keyarr, axis=axis) # this is not the most robust, but... if isinstance(labels, MultiIndex) and not isinstance(keyarr[0], tuple): level = 0 else: level = None return _reindex(keyarr, level=level)
def _getitem_iterable(self, key, axis=0): labels = self.obj._get_axis(axis) def _reindex(keys, level=None): try: return self.obj.reindex_axis(keys, axis=axis, level=level) except AttributeError: # Series assert axis == 0 return self.obj.reindex(keys, level=level) if com._is_bool_indexer(key): key = _check_bool_indexer(labels, key) return _reindex(labels[np.asarray(key)]) else: if isinstance(key, Index): # want Index objects to pass through untouched keyarr = key else: # asarray can be unsafe, NumPy strings are weird keyarr = _asarray_tuplesafe(key) if _is_integer_dtype(keyarr) and not _is_integer_index(labels): keyarr = labels.take(keyarr) # this is not the most robust, but... if isinstance(labels, MultiIndex) and not isinstance(keyarr[0], tuple): level = 0 else: level = None return _reindex(keyarr, level=level)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _convert_to_indexer(self, obj, axis=0): """ Convert indexing key into something we can use to do actual fancy indexing on an ndarray Examples ix[:5] -> slice(0, 5) ix[[1,2,3]] -> [1,2,3] ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz) Going by Zen of Python? "In the face of ambiguity, refuse the temptation to guess." raise AmbiguousIndexError with integer labels? - No, prefer label-based indexing """ labels = self.obj._get_axis(axis) is_int_index = _is_integer_index(labels) if com.is_integer(obj) and not is_int_index: return obj try: return labels.get_loc(obj) except (KeyError, TypeError): pass if isinstance(obj, slice): ltype = labels.inferred_type if ltype == "floating": int_slice = _is_int_slice(obj) else: # floats that are within tolerance of int used int_slice = _is_index_slice(obj) null_slice = obj.start is None and obj.stop is None # could have integers in the first level of the MultiIndex position_slice = ( int_slice and not ltype == "integer" and not isinstance(labels, MultiIndex) ) start, stop = obj.start, obj.stop # last ditch effort: if we are mixed and have integers try: if "mixed" in ltype and int_slice: if start is not None: i = labels.get_loc(start) if stop is not None: j = labels.get_loc(stop) position_slice = False except KeyError: if ltype == "mixed-integer": raise if null_slice or position_slice: slicer = obj else: try: i, j = labels.slice_locs(start, stop) slicer = slice(i, j, obj.step) except Exception: if _is_index_slice(obj): if labels.inferred_type == "integer": raise slicer = obj else: raise return slicer elif _is_list_like(obj): if com._is_bool_indexer(obj): objarr = _check_bool_indexer(labels, obj) return objarr else: objarr = _asarray_tuplesafe(obj) # If have integer labels, defer to label-based indexing if _is_integer_dtype(objarr) and not is_int_index: return objarr # this is not the most robust, but... if isinstance(labels, MultiIndex) and not isinstance(objarr[0], tuple): level = 0 _, indexer = labels.reindex(objarr, level=level) check = labels.levels[0].get_indexer(objarr) else: level = None indexer = check = labels.get_indexer(objarr) mask = check == -1 if mask.any(): raise KeyError("%s not in index" % objarr[mask]) return indexer else: return labels.get_loc(obj)
def _convert_to_indexer(self, obj, axis=0): """ Convert indexing key into something we can use to do actual fancy indexing on an ndarray Examples ix[:5] -> slice(0, 5) ix[[1,2,3]] -> [1,2,3] ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz) Going by Zen of Python? "In the face of ambiguity, refuse the temptation to guess." raise AmbiguousIndexError with integer labels? - No, prefer label-based indexing """ labels = self.obj._get_axis(axis) is_int_index = _is_integer_index(labels) if com.is_integer(obj) and not is_int_index: return obj try: return labels.get_loc(obj) except (KeyError, TypeError): pass if isinstance(obj, slice): int_slice = _is_index_slice(obj) null_slice = obj.start is None and obj.stop is None # could have integers in the first level of the MultiIndex position_slice = ( int_slice and not labels.inferred_type == "integer" and not isinstance(labels, MultiIndex) ) start, stop = obj.start, obj.stop # last ditch effort: if we are mixed and have integers try: if "mixed" in labels.inferred_type and int_slice: if start is not None: i = labels.get_loc(start) if stop is not None: j = labels.get_loc(stop) position_slice = False except KeyError: if labels.inferred_type == "mixed-integer": raise if null_slice or position_slice: slicer = obj else: try: i, j = labels.slice_locs(start, stop) slicer = slice(i, j, obj.step) except Exception: if _is_index_slice(obj): if labels.inferred_type == "integer": raise slicer = obj else: raise return slicer elif _is_list_like(obj): if com._is_bool_indexer(obj): objarr = _check_bool_indexer(labels, obj) return objarr else: objarr = _asarray_tuplesafe(obj) # If have integer labels, defer to label-based indexing if _is_integer_dtype(objarr) and not is_int_index: return objarr # this is not the most robust, but... if isinstance(labels, MultiIndex) and not isinstance(objarr[0], tuple): level = 0 _, indexer = labels.reindex(objarr, level=level) check = labels.levels[0].get_indexer(objarr) else: level = None indexer = check = labels.get_indexer(objarr) mask = check == -1 if mask.any(): raise KeyError("%s not in index" % objarr[mask]) return indexer else: return labels.get_loc(obj)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _get_slice_axis(self, slice_obj, axis=0): obj = self.obj axis_name = obj._get_axis_name(axis) labels = getattr(obj, axis_name) int_slice = _is_index_slice(slice_obj) start = slice_obj.start stop = slice_obj.stop # in case of providing all floats, use label-based indexing float_slice = labels.inferred_type == "floating" and _is_float_slice(slice_obj) null_slice = slice_obj.start is None and slice_obj.stop is None # could have integers in the first level of the MultiIndex, in which # case we wouldn't want to do position-based slicing position_slice = ( int_slice and labels.inferred_type != "integer" and not isinstance(labels, MultiIndex) and not float_slice ) # last ditch effort: if we are mixed and have integers try: if "mixed" in labels.inferred_type and int_slice: if start is not None: i = labels.get_loc(start) if stop is not None: j = labels.get_loc(stop) position_slice = False except KeyError: if labels.inferred_type == "mixed-integer": raise if null_slice or position_slice: slicer = slice_obj else: try: i, j = labels.slice_locs(start, stop) slicer = slice(i, j, slice_obj.step) except Exception: if _is_index_slice(slice_obj): if labels.inferred_type == "integer": raise slicer = slice_obj else: raise if not _need_slice(slice_obj): return obj return self._slice(slicer, axis=axis)
def _get_slice_axis(self, slice_obj, axis=0): obj = self.obj axis_name = obj._get_axis_name(axis) labels = getattr(obj, axis_name) int_slice = _is_index_slice(slice_obj) start = slice_obj.start stop = slice_obj.stop # in case of providing all floats, use label-based indexing float_slice = ( labels.inferred_type == "floating" and (type(start) == float or start is None) and (type(stop) == float or stop is None) ) null_slice = slice_obj.start is None and slice_obj.stop is None # could have integers in the first level of the MultiIndex, in which # case we wouldn't want to do position-based slicing position_slice = ( int_slice and labels.inferred_type != "integer" and not isinstance(labels, MultiIndex) and not float_slice ) # last ditch effort: if we are mixed and have integers try: if "mixed" in labels.inferred_type and int_slice: if start is not None: i = labels.get_loc(start) if stop is not None: j = labels.get_loc(stop) position_slice = False except KeyError: if labels.inferred_type == "mixed-integer": raise if null_slice or position_slice: slicer = slice_obj else: try: i, j = labels.slice_locs(start, stop) slicer = slice(i, j, slice_obj.step) except Exception: if _is_index_slice(slice_obj): if labels.inferred_type == "integer": raise slicer = slice_obj else: raise if not _need_slice(slice_obj): return obj return self._slice(slicer, axis=axis)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _is_integer_dtype(arr): return ( issubclass(arr.dtype.type, np.integer) and not arr.dtype.type == np.datetime64 )
def _is_integer_dtype(arr): return issubclass(arr.dtype.type, np.integer)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _is_list_like(obj): # Consider namedtuples to be not list like as they are useful as indices return ( np.iterable(obj) and not isinstance(obj, basestring) and not (isinstance(obj, tuple) and type(obj) is not tuple) )
def _is_list_like(obj): return np.iterable(obj) and not isinstance(obj, basestring)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _is_valid_index(x): return com.is_float(x)
def _is_valid_index(x): return ( com.is_integer(x) or com.is_float(x) and np.allclose(x, int(x), rtol=_eps, atol=0) )
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def ref_locs(self): if self._ref_locs is None: indexer = self.ref_items.get_indexer(self.items) indexer = com._ensure_platform_int(indexer) assert (indexer != -1).all() self._ref_locs = indexer return self._ref_locs
def ref_locs(self): if self._ref_locs is None: indexer = self.ref_items.get_indexer(self.items) assert (indexer != -1).all() self._ref_locs = indexer return self._ref_locs
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def fillna(self, value, inplace=False): new_values = self.values if inplace else self.values.copy() mask = com.isnull(new_values) np.putmask(new_values, mask, value) if inplace: return self else: return make_block(new_values, self.items, self.ref_items)
def fillna(self, value, inplace=False): new_values = self.values if inplace else self.values.copy() mask = com.isnull(new_values.ravel()) new_values.flat[mask] = value if inplace: return self else: return make_block(new_values, self.items, self.ref_items)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def interpolate(self, method="pad", axis=0, inplace=False, limit=None, missing=None): values = self.values if inplace else self.values.copy() if values.ndim != 2: raise NotImplementedError transf = (lambda x: x) if axis == 0 else (lambda x: x.T) if missing is None: mask = None else: # todo create faster fill func without masking mask = _mask_missing(transf(values), missing) if method == "pad": com.pad_2d(transf(values), limit=limit, mask=mask) else: com.backfill_2d(transf(values), limit=limit, mask=mask) return make_block(values, self.items, self.ref_items)
def interpolate(self, method="pad", axis=0, inplace=False): values = self.values if inplace else self.values.copy() if values.ndim != 2: raise NotImplementedError transf = (lambda x: x) if axis == 0 else (lambda x: x.T) if method == "pad": _pad(transf(values)) else: _backfill(transf(values)) return make_block(values, self.items, self.ref_items)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def should_store(self, value): return not issubclass( value.dtype.type, (np.integer, np.floating, np.complexfloating, np.bool_) )
def should_store(self, value): return not issubclass(value.dtype.type, (np.integer, np.floating, np.bool_))
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def make_block(values, items, ref_items, do_integrity_check=False): dtype = values.dtype vtype = dtype.type if issubclass(vtype, np.floating): klass = FloatBlock elif issubclass(vtype, np.complexfloating): klass = ComplexBlock elif issubclass(vtype, np.datetime64): klass = DatetimeBlock elif issubclass(vtype, np.integer): if vtype != np.int64: values = values.astype("i8") klass = IntBlock elif dtype == np.bool_: klass = BoolBlock else: klass = ObjectBlock return klass( values, items, ref_items, ndim=values.ndim, do_integrity_check=do_integrity_check, )
def make_block(values, items, ref_items, do_integrity_check=False): dtype = values.dtype vtype = dtype.type if issubclass(vtype, np.floating): klass = FloatBlock elif issubclass(vtype, np.integer): if vtype != np.int64: values = values.astype("i8") klass = IntBlock elif dtype == np.bool_: klass = BoolBlock else: klass = ObjectBlock return klass( values, items, ref_items, ndim=values.ndim, do_integrity_check=do_integrity_check, )
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def __setstate__(self, state): # discard anything after 3rd, support beta pickling format for a little # while longer ax_arrays, bvalues, bitems = state[:3] self.axes = [_ensure_index(ax) for ax in ax_arrays] self.axes = _handle_legacy_indexes(self.axes) blocks = [] for values, items in zip(bvalues, bitems): blk = make_block(values, items, self.axes[0], do_integrity_check=True) blocks.append(blk) self.blocks = blocks
def __setstate__(self, state): # discard anything after 3rd, support beta pickling format for a little # while longer ax_arrays, bvalues, bitems = state[:3] self.axes = [_ensure_index(ax) for ax in ax_arrays] blocks = [] for values, items in zip(bvalues, bitems): blk = make_block(values, items, self.axes[0], do_integrity_check=True) blocks.append(blk) self.blocks = blocks
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _verify_integrity(self): _union_block_items(self.blocks) mgr_shape = self.shape for block in self.blocks: assert block.ref_items is self.items assert block.values.shape[1:] == mgr_shape[1:] tot_items = sum(len(x.items) for x in self.blocks) assert len(self.items) == tot_items
def _verify_integrity(self): _union_block_items(self.blocks) mgr_shape = self.shape for block in self.blocks: assert block.values.shape[1:] == mgr_shape[1:] tot_items = sum(len(x.items) for x in self.blocks) assert len(self.items) == tot_items
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def get_numeric_data(self, copy=False): num_blocks = [ b for b in self.blocks if ( isinstance(b, (IntBlock, FloatBlock, ComplexBlock)) and not isinstance(b, DatetimeBlock) ) ] indexer = np.sort(np.concatenate([b.ref_locs for b in num_blocks])) new_items = self.items.take(indexer) new_blocks = [] for b in num_blocks: b = b.copy(deep=False) b.ref_items = new_items new_blocks.append(b) new_axes = list(self.axes) new_axes[0] = new_items return BlockManager(new_blocks, new_axes, do_integrity_check=False)
def get_numeric_data(self, copy=False): num_blocks = [b for b in self.blocks if isinstance(b, (IntBlock, FloatBlock))] indexer = np.sort(np.concatenate([b.ref_locs for b in num_blocks])) new_items = self.items.take(indexer) new_blocks = [] for b in num_blocks: b = b.copy(deep=False) b.ref_items = new_items new_blocks.append(b) new_axes = list(self.axes) new_axes[0] = new_items return BlockManager(new_blocks, new_axes, do_integrity_check=False)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def from_blocks(cls, blocks, index): # also checks for overlap items = _union_block_items(blocks) for blk in blocks: blk.ref_items = items return BlockManager(blocks, [items, index])
def from_blocks(cls, blocks, index): # also checks for overlap items = _union_block_items(blocks) return BlockManager(blocks, [items, index])
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _interleave(self, items): """ Return ndarray from blocks with specified item order Items must be contained in the blocks """ dtype = _interleaved_dtype(self.blocks) items = _ensure_index(items) result = np.empty(self.shape, dtype=dtype) itemmask = np.zeros(len(items), dtype=bool) # By construction, all of the item should be covered by one of the # blocks for block in self.blocks: indexer = items.get_indexer(block.items) assert (indexer != -1).all() result[indexer] = block.get_values(dtype) itemmask[indexer] = 1 assert itemmask.all() return result
def _interleave(self, items): """ Return ndarray from blocks with specified item order Items must be contained in the blocks """ dtype = _interleaved_dtype(self.blocks) items = _ensure_index(items) result = np.empty(self.shape, dtype=dtype) itemmask = np.zeros(len(items), dtype=bool) # By construction, all of the item should be covered by one of the # blocks for block in self.blocks: indexer = items.get_indexer(block.items) assert (indexer != -1).all() result[indexer] = block.values itemmask[indexer] = 1 assert itemmask.all() return result
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def reindex_items(self, new_items, copy=True, fill_value=np.nan): """ """ new_items = _ensure_index(new_items) data = self if not data.is_consolidated(): data = data.consolidate() return data.reindex_items(new_items) # TODO: this part could be faster (!) new_items, indexer = self.items.reindex(new_items) # could have some pathological (MultiIndex) issues here new_blocks = [] if indexer is None: for blk in self.blocks: if copy: new_blocks.append(blk.reindex_items_from(new_items)) else: blk.ref_items = new_items new_blocks.append(blk) else: for block in self.blocks: newb = block.reindex_items_from(new_items, copy=copy) if len(newb.items) > 0: new_blocks.append(newb) mask = indexer == -1 if mask.any(): extra_items = new_items[mask] na_block = self._make_na_block( extra_items, new_items, fill_value=fill_value ) new_blocks.append(na_block) new_blocks = _consolidate(new_blocks, new_items) return BlockManager(new_blocks, [new_items] + self.axes[1:])
def reindex_items(self, new_items, copy=True, fill_value=np.nan): """ """ new_items = _ensure_index(new_items) data = self if not data.is_consolidated(): data = data.consolidate() return data.reindex_items(new_items) # TODO: this part could be faster (!) new_items, indexer = self.items.reindex(new_items) # could have some pathological (MultiIndex) issues here new_blocks = [] if indexer is None: for blk in self.blocks: if copy: new_blocks.append(blk.reindex_items_from(new_items)) else: new_blocks.append(blk) else: for block in self.blocks: newb = block.reindex_items_from(new_items, copy=copy) if len(newb.items) > 0: new_blocks.append(newb) mask = indexer == -1 if mask.any(): extra_items = new_items[mask] na_block = self._make_na_block( extra_items, new_items, fill_value=fill_value ) new_blocks.append(na_block) new_blocks = _consolidate(new_blocks, new_items) return BlockManager(new_blocks, [new_items] + self.axes[1:])
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def rename_axis(self, mapper, axis=1): new_axis = Index([mapper(x) for x in self.axes[axis]]) assert new_axis.is_unique new_axes = list(self.axes) new_axes[axis] = new_axis return BlockManager(self.blocks, new_axes)
def rename_axis(self, mapper, axis=1): new_axis = Index([mapper(x) for x in self.axes[axis]]) new_axis._verify_integrity() new_axes = list(self.axes) new_axes[axis] = new_axis return BlockManager(self.blocks, new_axes)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def rename_items(self, mapper, copydata=True): new_items = Index([mapper(x) for x in self.items]) new_items.is_unique new_blocks = [] for block in self.blocks: newb = block.copy(deep=copydata) newb.set_ref_items(new_items, maybe_rename=True) new_blocks.append(newb) new_axes = list(self.axes) new_axes[0] = new_items return BlockManager(new_blocks, new_axes)
def rename_items(self, mapper, copydata=True): new_items = Index([mapper(x) for x in self.items]) new_items._verify_integrity() new_blocks = [] for block in self.blocks: newb = block.copy(deep=copydata) newb.set_ref_items(new_items, maybe_rename=True) new_blocks.append(newb) new_axes = list(self.axes) new_axes[0] = new_items return BlockManager(new_blocks, new_axes)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def fillna(self, value, inplace=False): new_blocks = [ b.fillna(value, inplace=inplace) if b._can_hold_na else b for b in self.blocks ] if inplace: return self return BlockManager(new_blocks, self.axes)
def fillna(self, value, inplace=False): """ """ new_blocks = [ b.fillna(value, inplace=inplace) if b._can_hold_na else b for b in self.blocks ] if inplace: return self return BlockManager(new_blocks, self.axes)
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def form_blocks(data, axes): # pre-filter out items if we passed it items = axes[0] if len(data) < len(items): extra_items = items - Index(data.keys()) else: extra_items = [] # put "leftover" items in float bucket, where else? # generalize? float_dict = {} complex_dict = {} int_dict = {} bool_dict = {} object_dict = {} datetime_dict = {} for k, v in data.iteritems(): if issubclass(v.dtype.type, np.floating): float_dict[k] = v elif issubclass(v.dtype.type, np.complexfloating): complex_dict[k] = v elif issubclass(v.dtype.type, np.datetime64): datetime_dict[k] = v elif issubclass(v.dtype.type, np.integer): int_dict[k] = v elif v.dtype == np.bool_: bool_dict[k] = v else: object_dict[k] = v blocks = [] if len(float_dict): float_block = _simple_blockify(float_dict, items, np.float64) blocks.append(float_block) if len(complex_dict): complex_block = _simple_blockify(complex_dict, items, np.complex128) blocks.append(complex_block) if len(int_dict): int_block = _simple_blockify(int_dict, items, np.int64) blocks.append(int_block) if len(datetime_dict): datetime_block = _simple_blockify(datetime_dict, items, np.dtype("M8[ns]")) blocks.append(datetime_block) if len(bool_dict): bool_block = _simple_blockify(bool_dict, items, np.bool_) blocks.append(bool_block) if len(object_dict) > 0: object_block = _simple_blockify(object_dict, items, np.object_) blocks.append(object_block) if len(extra_items): shape = (len(extra_items),) + tuple(len(x) for x in axes[1:]) block_values = np.empty(shape, dtype=float) block_values.fill(nan) na_block = make_block(block_values, extra_items, items, do_integrity_check=True) blocks.append(na_block) blocks = _consolidate(blocks, items) return blocks
def form_blocks(data, axes): # pre-filter out items if we passed it items = axes[0] if len(data) < len(items): extra_items = items - Index(data.keys()) else: extra_items = [] # put "leftover" items in float bucket, where else? # generalize? float_dict = {} int_dict = {} bool_dict = {} object_dict = {} for k, v in data.iteritems(): if issubclass(v.dtype.type, np.floating): float_dict[k] = v elif issubclass(v.dtype.type, np.integer): int_dict[k] = v elif v.dtype == np.bool_: bool_dict[k] = v else: object_dict[k] = v blocks = [] if len(float_dict): float_block = _simple_blockify(float_dict, items, np.float64) blocks.append(float_block) if len(int_dict): int_block = _simple_blockify(int_dict, items, np.int64) blocks.append(int_block) if len(bool_dict): bool_block = _simple_blockify(bool_dict, items, np.bool_) blocks.append(bool_block) if len(object_dict) > 0: object_block = _simple_blockify(object_dict, items, np.object_) blocks.append(object_block) if len(extra_items): shape = (len(extra_items),) + tuple(len(x) for x in axes[1:]) block_values = np.empty(shape, dtype=float) block_values.fill(nan) na_block = make_block(block_values, extra_items, items, do_integrity_check=True) blocks.append(na_block) blocks = _consolidate(blocks, items) return blocks
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _stack_dict(dct, ref_items, dtype): from pandas.core.series import Series # fml def _asarray_compat(x): # asarray shouldn't be called on SparseSeries if isinstance(x, Series): return x.values else: return np.asarray(x) def _shape_compat(x): # sparseseries if isinstance(x, Series): return (len(x),) else: return x.shape # index may box values items = ref_items[[x in dct for x in ref_items]] first = dct[items[0]] shape = (len(dct),) + _shape_compat(first) stacked = np.empty(shape, dtype=dtype) for i, item in enumerate(items): stacked[i] = _asarray_compat(dct[item]) # stacked = np.vstack([_asarray_compat(dct[k]) for k in items]) return items, stacked
def _stack_dict(dct, ref_items, dtype): from pandas.core.series import Series # fml def _asarray_compat(x): # asarray shouldn't be called on SparseSeries if isinstance(x, Series): return x.values else: return np.asarray(x) def _shape_compat(x): # sparseseries if isinstance(x, Series): return (len(x),) else: return x.shape items = [x for x in ref_items if x in dct] first = dct[items[0]] shape = (len(dct),) + _shape_compat(first) stacked = np.empty(shape, dtype=dtype) for i, item in enumerate(items): stacked[i] = _asarray_compat(dct[item]) # stacked = np.vstack([_asarray_compat(dct[k]) for k in items]) return items, stacked
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError
def _interleaved_dtype(blocks): from collections import defaultdict counts = defaultdict(lambda: 0) for x in blocks: counts[type(x)] += 1 have_int = counts[IntBlock] > 0 have_bool = counts[BoolBlock] > 0 have_object = counts[ObjectBlock] > 0 have_float = counts[FloatBlock] > 0 have_complex = counts[ComplexBlock] > 0 have_dt64 = counts[DatetimeBlock] > 0 have_numeric = have_float or have_complex or have_int if have_object or (have_bool and have_numeric) or (have_numeric and have_dt64): return np.dtype(object) elif have_bool: return np.dtype(bool) elif have_int and not have_float and not have_complex: return np.dtype("i8") elif have_dt64 and not have_float and not have_complex: return np.dtype("M8[ns]") elif have_complex: return np.dtype("c16") else: return np.dtype("f8")
def _interleaved_dtype(blocks): from collections import defaultdict counts = defaultdict(lambda: 0) for x in blocks: counts[type(x)] += 1 have_int = counts[IntBlock] > 0 have_bool = counts[BoolBlock] > 0 have_object = counts[ObjectBlock] > 0 have_float = counts[FloatBlock] > 0 have_numeric = have_float or have_int if have_object: return np.object_ elif have_bool and have_numeric: return np.object_ elif have_bool: return np.bool_ elif have_int and not have_float: return np.int64 else: return np.float64
https://github.com/pandas-dev/pandas/issues/1328
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>() ----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m') /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize) 1209 """ 1210 return DatetimeIndex(start=start, end=end, periods=periods, -> 1211 freq=freq, tz=tz, normalize=normalize) 1212 1213 /home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds) 202 203 if data is None and offset is None: --> 204 raise ValueError("Must provide freq argument if no data is " 205 "supplied") 206 ValueError: Must provide freq argument if no data is supplied
ValueError