本文整理汇总了Python中pandas.core.generic.NDFrame类的典型用法代码示例。如果您正苦于以下问题:Python NDFrame类的具体用法?Python NDFrame怎么用?Python NDFrame使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NDFrame类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _init_data
def _init_data(self, data, copy, dtype, **kwargs):
"""
Generate ND initialization; axes are passed
as required objects to __init__
"""
if data is None:
data = {}
if dtype is not None:
dtype = self._validate_dtype(dtype)
passed_axes = [kwargs.get(a) for a in self._AXIS_ORDERS]
axes = None
if isinstance(data, BlockManager):
if any(x is not None for x in passed_axes):
axes = [x if x is not None else y
for x, y in zip(passed_axes, data.axes)]
mgr = data
elif isinstance(data, dict):
mgr = self._init_dict(data, passed_axes, dtype=dtype)
copy = False
dtype = None
elif isinstance(data, (np.ndarray, list)):
mgr = self._init_matrix(data, passed_axes, dtype=dtype, copy=copy)
copy = False
dtype = None
else: # pragma: no cover
raise PandasError('Panel constructor not properly called!')
NDFrame.__init__(self, mgr, axes=axes, copy=copy, dtype=dtype)
示例2: TestNDFrame
class TestNDFrame(unittest.TestCase):
_multiprocess_can_split_ = True
def setUp(self):
tdf = t.makeTimeDataFrame()
self.ndf = NDFrame(tdf._data)
def test_constructor(self):
# with cast
ndf = NDFrame(self.ndf._data, dtype=np.int64)
self.assert_(ndf.values.dtype == np.int64)
def test_ndim(self):
self.assertEquals(self.ndf.ndim, 2)
def test_astype(self):
casted = self.ndf.astype(int)
self.assert_(casted.values.dtype == np.int_)
casted = self.ndf.astype(np.int32)
self.assert_(casted.values.dtype == np.int32)
def test_squeeze(self):
# noop
for s in [ t.makeFloatSeries(), t.makeStringSeries(), t.makeObjectSeries() ]:
t.assert_series_equal(s.squeeze(),s)
for df in [ t.makeTimeDataFrame() ]:
t.assert_frame_equal(df.squeeze(),df)
for p in [ t.makePanel() ]:
t.assert_panel_equal(p.squeeze(),p)
for p4d in [ t.makePanel4D() ]:
t.assert_panel4d_equal(p4d.squeeze(),p4d)
# squeezing
df = t.makeTimeDataFrame().reindex(columns=['A'])
t.assert_series_equal(df.squeeze(),df['A'])
p = t.makePanel().reindex(items=['ItemA'])
t.assert_frame_equal(p.squeeze(),p['ItemA'])
p = t.makePanel().reindex(items=['ItemA'],minor_axis=['A'])
t.assert_series_equal(p.squeeze(),p.ix['ItemA',:,'A'])
p4d = t.makePanel4D().reindex(labels=['label1'])
t.assert_panel_equal(p4d.squeeze(),p4d['label1'])
p4d = t.makePanel4D().reindex(labels=['label1'],items=['ItemA'])
t.assert_frame_equal(p4d.squeeze(),p4d.ix['label1','ItemA'])
示例3: __setitem__
def __setitem__(self, key, value):
_, N, K = self.shape
if isinstance(value, DataFrame):
value = value.reindex(index=self.major_axis, columns=self.minor_axis)
mat = value.values
elif isinstance(value, np.ndarray):
assert value.shape == (N, K)
mat = np.asarray(value)
elif np.isscalar(value):
dtype = _infer_dtype(value)
mat = np.empty((N, K), dtype=dtype)
mat.fill(value)
mat = mat.reshape((1, N, K))
NDFrame._set_item(self, key, mat)
示例4: panel4d_reindex
def panel4d_reindex(self, labs=None, labels=None, items=None, major_axis=None,
minor_axis=None, axis=None, **kwargs):
# Hack for reindex_axis deprecation
# Ha, we used labels for two different things
# I think this will work still.
if labs is None:
args = ()
else:
args = (labs,)
kwargs_ = dict(labels=labels,
items=items,
major_axis=major_axis,
minor_axis=minor_axis,
axis=axis)
kwargs_ = {k: v for k, v in kwargs_.items() if v is not None}
# major = kwargs.pop("major", None)
# minor = kwargs.pop('minor', None)
# if major is not None:
# if kwargs.get("major_axis"):
# raise TypeError("Cannot specify both 'major' and 'major_axis'")
# kwargs_['major_axis'] = major
# if minor is not None:
# if kwargs.get("minor_axis"):
# raise TypeError("Cannot specify both 'minor' and 'minor_axis'")
# kwargs_['minor_axis'] = minor
if axis is not None:
kwargs_['axis'] = axis
axes = validate_axis_style_args(self, args, kwargs_, 'labs', 'reindex')
kwargs.update(axes)
return NDFrame.reindex(self, **kwargs)
示例5: __setitem__
def __setitem__(self, key, value):
_, N, K = self.shape
if isinstance(value, DataFrame):
value = value.reindex(index=self.major_axis, columns=self.minor_axis)
mat = value.values
elif isinstance(value, np.ndarray):
if value.shape != (N, K):
raise AssertionError(("Shape of values must be (%d, %d), " "not (%d, %d)") % ((N, K) + values.shape))
mat = np.asarray(value)
elif np.isscalar(value):
dtype = _infer_dtype(value)
mat = np.empty((N, K), dtype=dtype)
mat.fill(value)
else:
raise TypeError("Cannot set item of type: %s" % str(type(value)))
mat = mat.reshape((1, N, K))
NDFrame._set_item(self, key, mat)
示例6: __setitem__
def __setitem__(self, key, value):
shape = tuple(self.shape)
if isinstance(value, self._constructor_sliced):
value = value.reindex(
**self._construct_axes_dict_for_slice(self._AXIS_ORDERS[1:]))
mat = value.values
elif isinstance(value, np.ndarray):
if not ((value.shape == shape[1:])):
raise AssertionError()
mat = np.asarray(value)
elif np.isscalar(value):
dtype, value = _infer_dtype_from_scalar(value)
mat = np.empty(shape[1:], dtype=dtype)
mat.fill(value)
else:
raise TypeError('Cannot set item of type: %s' % str(type(value)))
mat = mat.reshape(tuple([1]) + shape[1:])
NDFrame._set_item(self, key, mat)
示例7: __setitem__
def __setitem__(self, key, value):
shape = tuple(self.shape)
if isinstance(value, self._constructor_sliced):
value = value.reindex(**self._construct_axes_dict_for_slice(self._AXIS_ORDERS[1:]))
mat = value.values
elif isinstance(value, np.ndarray):
if value.shape != shape[1:]:
raise ValueError(
"shape of value must be {0}, shape of given " "object was {1}".format(shape[1:], value.shape)
)
mat = np.asarray(value)
elif np.isscalar(value):
dtype, value = _infer_dtype_from_scalar(value)
mat = np.empty(shape[1:], dtype=dtype)
mat.fill(value)
else:
raise TypeError("Cannot set item of type: %s" % str(type(value)))
mat = mat.reshape(tuple([1]) + shape[1:])
NDFrame._set_item(self, key, mat)
示例8: __init__
def __init__(self, data=None, items=None, major_axis=None, minor_axis=None,
copy=False, dtype=None):
"""
Represents wide format panel data, stored as 3-dimensional array
Parameters
----------
data : ndarray (items x major x minor), or dict of DataFrames
items : Index or array-like
axis=1
major_axis : Index or array-like
axis=1
minor_axis : Index or array-like
axis=2
dtype : dtype, default None
Data type to force, otherwise infer
copy : boolean, default False
Copy data from inputs. Only affects DataFrame / 2d ndarray input
"""
if data is None:
data = {}
passed_axes = [items, major_axis, minor_axis]
axes = None
if isinstance(data, BlockManager):
if any(x is not None for x in passed_axes):
axes = [x if x is not None else y
for x, y in zip(passed_axes, data.axes)]
mgr = data
elif isinstance(data, dict):
mgr = self._init_dict(data, passed_axes, dtype=dtype)
copy = False
dtype = None
elif isinstance(data, (np.ndarray, list)):
mgr = self._init_matrix(data, passed_axes, dtype=dtype, copy=copy)
copy = False
dtype = None
else: # pragma: no cover
raise PandasError('Panel constructor not properly called!')
NDFrame.__init__(self, mgr, axes=axes, copy=copy, dtype=dtype)
示例9: pop
def pop(self, item):
"""
Return item slice from panel and delete from panel
Parameters
----------
key : object
Must be contained in panel's items
Returns
-------
y : DataFrame
"""
return NDFrame.pop(self, item)
示例10: __setitem__
def __setitem__(self, key, value):
_, N, K = self.shape
# XXX
if isinstance(value, LongPanel):
if len(value.items) != 1:
raise ValueError('Input panel must have only one item!')
value = value.to_wide()[value.items[0]]
if isinstance(value, DataFrame):
value = value.reindex(index=self.major_axis,
columns=self.minor_axis)
mat = value.values
elif isinstance(value, np.ndarray):
assert(value.shape == (N, K))
mat = np.asarray(value)
elif np.isscalar(value):
dtype = _infer_dtype(value)
mat = np.empty((N, K), dtype=dtype)
mat.fill(value)
mat = mat.reshape((1, N, K))
NDFrame._set_item(self, key, mat)
示例11: TestNDFrame
class TestNDFrame(unittest.TestCase):
def setUp(self):
tdf = t.makeTimeDataFrame()
self.ndf = NDFrame(tdf._data)
def test_constructor(self):
# with cast
ndf = NDFrame(self.ndf._data, dtype=np.int64)
self.assert_(ndf.values.dtype == np.int64)
def test_ndim(self):
self.assertEquals(self.ndf.ndim, 2)
def test_astype(self):
casted = self.ndf.astype(int)
self.assert_(casted.values.dtype == np.int64)
示例12: __init__
def __init__(self, data=None, index=None, columns=None,
default_kind=None, default_fill_value=None,
dtype=None, copy=False):
# pick up the defaults from the Sparse structures
if isinstance(data, SparseDataFrame):
if index is None:
index = data.index
if columns is None:
columns = data.columns
if default_fill_value is None:
default_fill_value = data.default_fill_value
if default_kind is None:
default_kind = data.default_kind
elif isinstance(data, (SparseSeries, SparseArray)):
if index is None:
index = data.index
if default_fill_value is None:
default_fill_value = data.fill_value
if columns is None and hasattr(data, 'name'):
columns = [data.name]
if columns is None:
raise Exception("cannot pass a series w/o a name or columns")
data = {columns[0]: data}
if default_fill_value is None:
default_fill_value = np.nan
if default_kind is None:
default_kind = 'block'
self._default_kind = default_kind
self._default_fill_value = default_fill_value
if isinstance(data, dict):
mgr = self._init_dict(data, index, columns)
if dtype is not None:
mgr = mgr.astype(dtype)
elif isinstance(data, (np.ndarray, list)):
mgr = self._init_matrix(data, index, columns)
if dtype is not None:
mgr = mgr.astype(dtype)
elif isinstance(data, SparseDataFrame):
mgr = self._init_mgr(
data._data, dict(index=index, columns=columns), dtype=dtype, copy=copy)
elif isinstance(data, DataFrame):
mgr = self._init_dict(data, data.index, data.columns)
if dtype is not None:
mgr = mgr.astype(dtype)
elif isinstance(data, BlockManager):
mgr = self._init_mgr(
data, axes=dict(index=index, columns=columns), dtype=dtype, copy=copy)
elif data is None:
data = {}
if index is None:
index = Index([])
else:
index = _ensure_index(index)
if columns is None:
columns = Index([])
else:
for c in columns:
data[c] = SparseArray(np.nan,
index=index,
kind=self._default_kind,
fill_value=self._default_fill_value)
mgr = dict_to_manager(data, columns, index)
if dtype is not None:
mgr = mgr.astype(dtype)
NDFrame.__init__(self, mgr)
示例13: setUp
def setUp(self):
tdf = t.makeTimeDataFrame()
self.ndf = NDFrame(tdf._data)