从Dataframe的一行获取数据的子集

时间:2017-06-06 18:13:12

标签: python pandas dataframe indexing

假设我有一个数据帧df,其列为'A','B','C' 现在我只想提取df的第2行,只提取列'B'和'C'。最有效的方法是什么?

你能否告诉我为什么df.ix [2,['B','C']]不起作用?

谢谢!

2 个答案:

答案 0 :(得分:2)

def blocks(img, rows, cols): h, w = img.shape[:2] xs = np.uint32(np.rint(np.linspace(0, w, num=cols+1))) ys = np.uint32(np.rint(np.linspace(0, h, num=rows+1))) ystarts, yends = ys[:-1], ys[1:] xstarts, xends = xs[:-1], xs[1:] for y1, y2 in zip(ystarts, yends): for x1, x2 in zip(xstarts, xends): yield img[y1:y2, x1:x2]

OR

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

答案 1 :(得分:2)

考虑数据框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

如果您想维护数据框

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

   B  C
y  4  5

如果你想要一个系列

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

B    4
C    5
Name: y, dtype: int64
相关问题