R to Python subsetting via vector

Question:

I’m a python newbie but have some R experience. In R if I’d like to subset a data.frame I can use a variable to do something like this:

# Columns

# Assign column names to variable
colsToUse <- c('col1','col2','col3')

# Use variable to subset
df2 <- df1[,colsToUse]

# Rows

# Assign column names to variable
rowsToUse <- sample(1:nrows(df1), 500)

# Use variable to subset
df3 <- df1[rowsToUse,]

How would I do this in python?

Asked By: screechOwl

||

Answers:

Based on your stated use of pandas

colsToUse = ['col1', 'col2', 'col3']
rowsToUse = np.random.choice(range(len(df1)), 500)

df2 = df1.ix[:, colsToUse]
df3 = df1.ix[rowsToUse, :]

There are also some other DataFrame helper functions for indexing: df1.loc, df1.iloc, and df1.xs.

It’s also helpful to look at the guide NumPy for MATLAB Users which also often answers questions for R users too, at least when dealing with just a numpy.ndarray).

Answered By: ely
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.