在数据框中搜索索引值

时间:2020-06-29 00:45:00

标签: python pandas

我要根据索引值设置不同的条件。

我有以下索引值:

country

Uk
Us
Es
In
It
Ge
Ho

国家(地区)是我数据框中的索引。 我需要执行以下操作

  • 如果索引值等于'Uk',则执行某些操作;
  • 如果索引值等于“ Us”,则执行其他操作;

以此类推。

我尝试如下

 if df.index.isin(['Us']) or df.isin(['Uk']):
        stop_words = stopwords.words('english')
    if df.index.isin(['Es']):
        stop_words = stopwords.words('spanish')  

但这是错误的方法。我不熟悉pandas数据框中的索引,因为我一直使用列。 感谢您的帮助和建议。

1 个答案:

答案 0 :(得分:1)

您可以使用.loc()

选择数据框的索引
df.loc['US', 'stop_words'] = 'english'
df.loc['UK', 'stop_words'] = 'english'
df.loc['ES', 'stop_words'] = 'spanish'

此示例将根据索引创建一个包含英语或西班牙语的新列stop_words