I want to use the equivalent of the subset command in R for some Python code I am writing.
Here is my data:
col1 col2 col3 col4 col5
100002 2006 1.1 0.01 6352
100002 2006 1.2 0.84 304518
100002 2006 2 1.52 148219
100002 2007 1.1 0.01 6292
10002 2006 1.1 0.01 5968
10002 2006 1.2 0.25 104318
10002 2007 1.1 0.01 6800
10002 2007 4 2.03 25446
10002 2008 1.1 0.01 6408
I want to subset the data based on contents of col1
and col2
. (The unique values in col1 are 100002 and 10002, and in col2 are 2006,2007 and 2008.)
This can be done in R using the subset command, is there anything similar in Python?
subset()
in R is pretty much analogous tofilter()
in Python. As the reference notes, this will be used implicitly by list comprehensions, so the most concise and clear way to write the code might beif, for example, your data rows were in an iterable called
items
.While the iterator-based answers are perfectly fine, if you're working with numpy arrays (as you mention that you are) there are better and faster ways of selecting things:
This yields
subset1:
subset2:
If you didn't know the unique values in the first column beforehand, you can use either
numpy.unique1d
or the builtin functionset
to find them.Edit: I just realized that you wanted to select data where you have unique combinations of two columns... In that case, you might do something like this:
(I'm storing the subsets as a dict, with the key being a tuple of the combination... There are certainly other (and better, depending on what you're doing) ways to do this!)
Since I'm not familiar with R nor how this subset command works based upon your description I can suggest you take a look at itertool's groupby functionality. If given a function which outputs a value, you can form groups based upon that function's output. Taken from groupby:
and then you've got your subsets. However, do be careful as the values returned are not full fledged lists. They're iterators.
I am assuming that your values are being returned on a row-by-row basis.