Python Pandas DataFrame如果索引包含任何字符串值,则应用标签,否则应用不同的标签

时间:2015-06-04 04:06:24

标签: python numpy pandas dataframe

我有一个输出下表的数据框。请注意'搜索字词'是指数。

Search term                 Impressions Clicks  Cost     Converted clicks
american brewing            286446      104862  8034.18  6831
american brewing supplies   165235      64764   3916.48  4106
brewing supplies            123598      8131    6941.87  278
wine bottles                272969      7438    4944.7   194
www americanbrewing com     2782        1163    227.17   120
home brewing                216138      3744    3468.24  110
wine making                 147985      6602    5024.54  108

如果搜索字词' (索引)包含'american brewing''americanbrewing',应用标签'Brand',否则将'Non-brand'应用于标题为Label的列。

Search term                 Impressions Clicks  Cost     Converted clicks    Label
american brewing            286446      104862  8034.18  6831                Brand
american brewing supplies   165235      64764   3916.48  4106                Brand
brewing supplies            123598      8131    6941.87  278                 Non-brand
wine bottles                272969      7438    4944.7   194                 Non-brand
www americanbrewing com     2782        1163    227.17   120                 Brand
home brewing                216138      3744    3468.24  110                 Non-brand
wine making                 147985      6602    5024.54  108                 Non-brand

我在StackOverflow上看到过很多这样的例子:

df['Label'] = df[df['SomeColumn'].str.contains('american brewing|americanbrewing')]

但这不起作用,因为我的'SomeColumn'df.index,当我尝试类似的事情时:

df['Label'] = df[df.index.str.contains('american brewing|americanbrewing')]

我收到错误AttributeError: 'Index' object has no attribute 'str'

我还看到了使用np.where的示例看起来很有希望,但我仍遇到同样的问题,因为'Search term'不是列,而是index

df['Label'] = np.where(df['Search term'].str.contains('american brewing|americanbrewing', 'Brand', 'Non-brand')

这是我的完整代码:

import pandas as pd
import numpy as np

brand_terms = ['american brewing', 'americanbrewing']

data = pd.read_csv(r'sqr.csv', encoding='cp1252')

df = pd.DataFrame(data)
df['Search term'] = df['Search term'].replace(r'[^\w&\' ]', '', regex=True)
df['Cost'] = df['Cost'].replace(r'[^\d\.]', '', regex=True).astype('float')
#print(df.dtypes)
grouped = df.groupby('Search term')
result = grouped[['Impressions', 'Clicks', 'Cost', 'Converted clicks']].sum()
result = result.sort(['Converted clicks','Cost'], ascending=False)

#This doesn't work
result['Label'] = result.where(result['Search term'].str.contains('|'.join(brand_terms), 'Brand', 'Non-brand'))

result.to_csv('sqr_aggregate.csv')

如果Label(索引)包含多个可能的字符串值中的任何一个,我如何根据result dataframe输出Search term列?在True,应用Brand的情况下,将Non-brand应用于Label列。

2 个答案:

答案 0 :(得分:1)

如果您不想重置索引,可以采用以下方法。

您可以将index转换为Series并应用转换。

In [16]: np.where(pd.Series(df.index).str.contains('american brewing|americanbrewing'),
                  'Brand', 'Non-Brand')
Out[16]:
array(['Brand', 'Brand', 'Non-Brand', 'Non-Brand', 'Brand', 'Non-Brand',
       'Non-Brand'],
      dtype='|S9')

答案 1 :(得分:0)

尝试更改代码以使用df.groupby('Search term', as_index = False)