简体   繁体   中英

Get a subset of data from one row of Dataframe

Let's say I have a dataframe df with columns 'A', 'B', 'C' Now I just want to extract row 2 of df and only columns 'B' and 'C'. What is the most efficient way to do that?

Can you please tell me why df.ix[2, ['B', 'C']] didn't work?

Thank you!

row_2 = df[['B', 'C']].iloc[1]

或者

# Convert column to 2xN vector, grab row 2 row_2 = list(df[['B', 'C']].apply(tuple, axis=1))[1]

Consider the dataframe df

df = pd.DataFrame(np.arange(9).reshape(3, 3), list('xyz'), list('ABC'))
df

   A  B  C
x  0  1  2
y  3  4  5
z  6  7  8

If you want to maintain a dataframe

df.loc[df.index[[1]], ['B', 'C']]

   B  C
y  4  5

If you want a series

df.loc[df.index[1], ['B', 'C']]

B    4
C    5
Name: y, dtype: int64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM