Skip to content

ENH add sample #2419 #7274

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/v0.14.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ Known Issues
Enhancements
~~~~~~~~~~~~

- Add a sample method to NDFrame (:issue:`2419`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you make sample a link? :func:~DataFrame.sample``?


.. _whatsnew_0141.performance:

Performance
Expand Down
39 changes: 39 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1241,6 +1241,45 @@ def take(self, indices, axis=0, convert=True, is_copy=True):

return result

def sample(self, size, replace=True):
"""Take a sample from the object, analogue of numpy.random.choice

Parameters
----------
size : int, size of sample to take
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you adhere to the numpy docstring standard?

arg : type
    Explanation

replace : bool, default True, whether to sample with replacements

Returns
-------
type of caller

Examples
--------
>>> s = pd.Series([1, 2, 3, 4, 5])
>>> s.sample(3, replace=False)
2 3
0 1
3 4
dtype: int64
>>> s.sample(3, replace=True)
1 2
3 4
1 2
dtype: int64

Note
----
If you are sampling without replacement over a larger sample size than
the object you're sampling a ValueError will be raised.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can also add that this is equivalent/related to the numpy.random.choice function?


"""
try:
from numpy.random import choice
except ImportError:
from pandas.stats.misc import choice
msk = choice(len(self), size, replace=replace)
return self.iloc[msk]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should use take, which is faster


def xs(self, key, axis=0, level=None, copy=None, drop_level=True):
"""
Returns a cross-section (row(s) or column(s)) from the Series/DataFrame.
Expand Down
17 changes: 17 additions & 0 deletions pandas/stats/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,3 +297,20 @@ def _bucket_labels(series, k):
mat[v] = i

return mat + 1


def choice(arr, size, replace):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

forgot that arr can be an int. Also, I should make the private.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't need this anymore since we require numpy 1.7 now

"""Partial implementation of numpy.random.choice which is new to 1.7

Note: unlike numpy's version size must be a scalar.
"""
if replace:
pos = (np.random.sample(size) * len(arr)).astype('int64')
return arr[pos]
else:
if size > len(arr):
raise ValueError("Cannot take a larger sample than "
"population when 'replace=False'")
shuffle = np.arange(len(arr))
np.random.shuffle(shuffle)
return arr[shuffle[:size]]
6 changes: 6 additions & 0 deletions pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -8441,6 +8441,12 @@ def test_truncate_copy(self):
truncated.values[:] = 5.
self.assertFalse((self.tsframe.values[5:11] == 5).any())

def test_sample(self):
df = DataFrame([[1, 2], [2, 3]], columns=['A', 'B'])
res = df.sample(5)
self.assertEqual(len(res), 5)
assert(res.index.isin(df.index).all())

def test_xs(self):
idx = self.frame.index[5]
xs = self.frame.xs(idx)
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/test_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,12 @@ def test_xs(self):
result = self.panel.xs('D', axis=2)
self.assertIsNotNone(result.is_copy)

def test_sample(self):
p = self.panel
res = p.sample(5)
self.assertEqual(len(res), 5)
assert(res.major_axis.isin(p.major_axis).all())

def test_getitem_fancy_labels(self):
p = self.panel

Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1608,6 +1608,12 @@ def test_mask(self):
rs = s.where(cond, np.nan)
assert_series_equal(rs, s.mask(~cond))

def test_sample(self):
s = Series([1, 2, 2, 3])
res = s.sample(5)
self.assertEqual(len(res), 5)
assert(res.index.isin(s.index).all())

def test_drop(self):

# unique
Expand Down