【问题标题】:Select rows from a DataFrame based on multiple values in a column in pandas [duplicate]根据熊猫中一列中的多个值从DataFrame中选择行[重复]
【发布时间】:2016-07-24 10:23:10
【问题描述】:

这不是一个重复的问题,但类似于

Select rows from a DataFrame based on values in a column in pandas

在上一个链接中的那个答案中,它仅基于一个标准,如果我有多个标准怎么办。

我想在一列中选择多行,而不仅仅是基于特定值的行。为了争论起见,请考虑世界银行的 DataFrame

import pandas.io.wb as wb
import pandas as pd
import numpy as np
df2= wb.get_indicators()

我选择某个特定值的方式就是这样

df2.loc[df2['id'] == 'SP.POP.TOTL']

df2.loc[df2['id'] == 'NY.GNP.PCAP.CD']

如何在一个新数据框中同时选择 3 或 4?这样的行是:

'SP.POP.TOTL'
'NY.GNP.PCAP.CD'

提前谢谢你

【问题讨论】:

  • 这与您链接的问题的答案有何不同,后者在第二句中给出了isin 示例?

标签: python pandas dataframe


【解决方案1】:

你可以使用.isin():

In [28]: df2[df2['id'].isin(['SP.POP.TOTL','NY.GNP.PCAP.CD'])]
Out[28]:
                  id                                        name  \
7478  NY.GNP.PCAP.CD  GNI per capita, Atlas method (current US$)
9568     SP.POP.TOTL                           Population, total

                            source  \
7478  World Development Indicators
9568  World Development Indicators

                                             sourceNote  \
7478  GNI per capita (formerly GNP per capita) is th...
9568  Total population is based on the de facto defi...

                                     sourceOrganization  \
7478  b'World Bank national accounts data, and OECD ...
9568  b'(1) United Nations Population Division. Worl...

                                 topics
7478  Economy & Growth ; Climate Change
9568           Health  ; Climate Change

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-05
    • 2015-10-23
    相关资源
    最近更新 更多