从另一个DataFrame的索引列表中提取DataFrame [英] Extract DataFrame from a list of indices of another DataFrame

查看:560
本文介绍了从另一个DataFrame的索引列表中提取DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框 A和一个索引列表 I。我想生成/获取一个仅包含原始DataFrame A的那些索引 I中的数据的DataFrame B。我该如何实现?

I've a DataFrame "A" and a list of indices "I". I want to generate/get a DataFrame "B" which contains only the data in those indices "I" of the original DataFrame "A". How can I achieve this?

假设 I = [1,3] ,我尝试了此 A.filter( items = I,axis = 0)是正确的方法,还是有更好的方法呢?

Assuming I = [1, 3] , I tried this A.filter(items=I, axis=0) is this the right way, or is there an even better way to do it.

推荐答案

我认为需要 DataFrame.loc

I think to need DataFrame.loc:

A = pd.DataFrame({
    'A': ['a','a','a','a','b','b','b','c','d'],
    'B': list(range(9))
})
print (A)
   A  B
0  a  0
1  a  1
2  a  2
3  a  3
4  b  4
5  b  5
6  b  6
7  c  7

I = [1,3]
B = A.loc[I]
print (B)
   A  B
1  a  1
3  a  3

这篇关于从另一个DataFrame的索引列表中提取DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆