本文整理汇总了Python中pandas.core.api.Series类的典型用法代码示例。如果您正苦于以下问题:Python Series类的具体用法?Python Series怎么用?Python Series使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Series类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_categorical_zeroes
def test_categorical_zeroes(self):
# keep the `d` category with 0
s = Series(pd.Categorical(
list('bbbaac'), categories=list('abcd'), ordered=True))
result = s.value_counts()
expected = Series([3, 2, 1, 0], index=pd.Categorical(
['b', 'a', 'c', 'd'], categories=list('abcd'), ordered=True))
tm.assert_series_equal(result, expected, check_index_type=True)
示例2: test_save_load
def test_save_load(self):
self.series.save('tmp1')
self.ts.save('tmp3')
unp_series = Series.load('tmp1')
unp_ts = Series.load('tmp3')
os.remove('tmp1')
os.remove('tmp3')
assert_series_equal(unp_series, self.series)
assert_series_equal(unp_ts, self.ts)
示例3: percentileRank
def percentileRank(frame, column=None, kind='mean'):
"""
Return score at percentile for each point in time (cross-section)
Parameters
----------
frame: DataFrame
column: string or Series, optional
Column name or specific Series to compute percentiles for.
If not provided, percentiles are computed for all values at each
point in time. Note that this can take a LONG time.
kind: {'rank', 'weak', 'strict', 'mean'}, optional
This optional parameter specifies the interpretation of the
resulting score:
- "rank": Average percentage ranking of score. In case of
multiple matches, average the percentage rankings of
all matching scores.
- "weak": This kind corresponds to the definition of a cumulative
distribution function. A percentileofscore of 80%
means that 80% of values are less than or equal
to the provided score.
- "strict": Similar to "weak", except that only values that are
strictly less than the given score are counted.
- "mean": The average of the "weak" and "strict" scores, often used in
testing. See
http://en.wikipedia.org/wiki/Percentile_rank
See also
--------
scipy.stats.percentileofscore
Returns
-------
TimeSeries or DataFrame, depending on input
"""
from scipy.stats import percentileofscore
fun = lambda xs, score: percentileofscore(remove_na(xs),
score, kind=kind)
results = {}
framet = frame.T
if column is not None:
if isinstance(column, Series):
for date, xs in frame.T.iteritems():
results[date] = fun(xs, column.get(date, NaN))
else:
for date, xs in frame.T.iteritems():
results[date] = fun(xs, xs[column])
results = Series(results)
else:
for column in frame.columns:
for date, xs in framet.iteritems():
results.setdefault(date, {})[column] = fun(xs, xs[column])
results = DataFrame(results).T
return results
示例4: _nobs_raw
def _nobs_raw(self):
if self._is_rolling:
window = self._window
else:
# expanding case
window = len(self._index)
result = Series(self._time_obs_count).rolling(window, min_periods=1).sum().values
return result.astype(int)
示例5: test_fromValue
def test_fromValue(self):
nans = Series.fromValue(np.NaN, index=self.ts.index)
self.assert_(nans.dtype == np.float_)
strings = Series.fromValue('foo', index=self.ts.index)
self.assert_(strings.dtype == np.object_)
d = datetime.now()
dates = Series.fromValue(d, index=self.ts.index)
self.assert_(dates.dtype == np.object_)
示例6: test_merge_int
def test_merge_int(self):
left = Series({'a' : 1., 'b' : 2., 'c' : 3., 'd' : 4})
right = Series({1 : 11, 2 : 22, 3 : 33})
self.assert_(left.dtype == np.float_)
self.assert_(issubclass(right.dtype.type, np.integer))
merged = left.merge(right)
self.assert_(merged.dtype == np.float_)
self.assert_(isnull(merged['d']))
self.assert_(not isnull(merged['c']))
示例7: test_categorical
def test_categorical(self):
s = Series(pd.Categorical(list('aaabbc')))
result = s.value_counts()
expected = pd.Series([3, 2, 1], index=pd.CategoricalIndex(['a', 'b', 'c']))
tm.assert_series_equal(result, expected, check_index_type=True)
# preserve order?
s = s.cat.as_ordered()
result = s.value_counts()
expected.index = expected.index.as_ordered()
tm.assert_series_equal(result, expected, check_index_type=True)
示例8: y_fitted
def y_fitted(self):
"""Returns the fitted y values. This equals BX."""
if self._weights is None:
index = self._x_filtered.index
orig_index = index
else:
index = self._y.index
orig_index = self._y_orig.index
result = Series(self._y_fitted_raw, index=index)
return result.reindex(orig_index)
示例9: test_fill
def test_fill(self):
ts = Series([0., 1., 2., 3., 4.], index=common.makeDateIndex(5))
self.assert_(np.array_equal(ts, ts.fill()))
ts[2] = np.NaN
self.assert_(np.array_equal(ts.fill(), [0., 1., 1., 3., 4.]))
self.assert_(np.array_equal(ts.fill(method='backfill'), [0., 1., 3., 3., 4.]))
self.assert_(np.array_equal(ts.fill(value=5), [0., 1., 5., 3., 4.]))
示例10: test_iloc_setitem_series
def test_iloc_setitem_series(self):
s = Series(np.random.randn(10), index=range(0,20,2))
s.iloc[1] = 1
result = s.iloc[1]
self.assert_(result == 1)
s.iloc[:4] = 0
expected = s.iloc[:4]
result = s.iloc[:4]
assert_series_equal(result, expected)
示例11: test_reindex_int
def test_reindex_int(self):
ts = self.ts[::2]
int_ts = Series(np.zeros(len(ts), dtype=int), index=ts.index)
# this should work fine
reindexed_int = int_ts.reindex(self.ts.index)
# if NaNs introduced
self.assert_(reindexed_int.dtype == np.float_)
# NO NaNs introduced
reindexed_int = int_ts.reindex(int_ts.index[::2])
self.assert_(reindexed_int.dtype == np.int_)
示例12: test_firstValid
def test_firstValid(self):
ts = self.ts.copy()
ts[:5] = np.NaN
index = ts._firstTimeWithValue()
self.assertEqual(index, ts.index[5])
ts[-5:] = np.NaN
index = ts._lastTimeWithValue()
self.assertEqual(index, ts.index[-6])
ser = Series([], index=[])
self.assert_(ser._lastTimeWithValue() is None)
self.assert_(ser._firstTimeWithValue() is None)
示例13: test_value_counts
def test_value_counts(self):
np.random.seed(1234)
from pandas.tools.tile import cut
arr = np.random.randn(4)
factor = cut(arr, 4)
tm.assertIsInstance(factor, Categorical)
result = algos.value_counts(factor)
cats = ['(-1.194, -0.535]', '(-0.535, 0.121]', '(0.121, 0.777]',
'(0.777, 1.433]']
expected_index = CategoricalIndex(cats, cats, ordered=True)
expected = Series([1, 1, 1, 1], index=expected_index)
tm.assert_series_equal(result.sort_index(), expected.sort_index())
示例14: test_categorical_nans
def test_categorical_nans(self):
s = Series(pd.Categorical(list('aaaaabbbcc'))) # 4,3,2,1 (nan)
s.iloc[1] = np.nan
result = s.value_counts()
expected = pd.Series([4, 3, 2], index=pd.CategoricalIndex(
['a', 'b', 'c'], categories=['a', 'b', 'c']))
tm.assert_series_equal(result, expected, check_index_type=True)
result = s.value_counts(dropna=False)
expected = pd.Series([
4, 3, 2, 1
], index=pd.CategoricalIndex(['a', 'b', 'c', np.nan]))
tm.assert_series_equal(result, expected, check_index_type=True)
# out of order
s = Series(pd.Categorical(
list('aaaaabbbcc'), ordered=True, categories=['b', 'a', 'c']))
s.iloc[1] = np.nan
result = s.value_counts()
expected = pd.Series([4, 3, 2], index=pd.CategoricalIndex(
['a', 'b', 'c'], categories=['b', 'a', 'c'], ordered=True))
tm.assert_series_equal(result, expected, check_index_type=True)
result = s.value_counts(dropna=False)
expected = pd.Series([4, 3, 2, 1], index=pd.CategoricalIndex(
['a', 'b', 'c', np.nan], categories=['b', 'a', 'c'], ordered=True))
tm.assert_series_equal(result, expected, check_index_type=True)
示例15: test_value_counts_normalized
def test_value_counts_normalized(self):
# GH12558
s = Series([1, 2, np.nan, np.nan, np.nan])
dtypes = (np.float64, np.object, 'M8[ns]')
for t in dtypes:
s_typed = s.astype(t)
result = s_typed.value_counts(normalize=True, dropna=False)
expected = Series([0.6, 0.2, 0.2],
index=Series([np.nan, 2.0, 1.0], dtype=t))
tm.assert_series_equal(result, expected)
result = s_typed.value_counts(normalize=True, dropna=True)
expected = Series([0.5, 0.5],
index=Series([2.0, 1.0], dtype=t))
tm.assert_series_equal(result, expected)