1 Вопрос: Пустой фрейм данных печатается при отсутствии совпадений

вопрос создан в Mon, Mar 18, 2019 12:00 AM

smer_prods - это словарь, каждый ключ которого содержит список в качестве значения:

smer_prods = {
    'ragi vermicelli' : ['ragi vermicelli'],
    'rice vermicelli' : ['rice vermicelli'],
    'vermicelli jupiter' : ['vermicelli jupiter'],
    'lemon & tamarind vermicelli' : ['lemon & tamarind vermicelli'],
    'finosta vermicelli' : ['finosta vermicelli-5kg'],
    'rosted vermicelli' : ['roasted vermicelli'],
    'semiya/vermicelli' : ['semiya / vermicelli 900grams'],
    'red chili' : ['red chilli (lal mirch)','guntur red chilli','red chilly whole(lal mirch)', 'red chilly wg', 'red chilli whole (hot) 1 kg', 'red chilli whole (rich colour) 1 kg'],
    'red chili powder' : ['red chilli fresh-kg','red chilli powder (rich colour) 1 kg','red chilli powder (hot) 1 kg','red chilli powder','lal mirch powder','lal mirch powder 100gms', 'lal mirch powder 1kg', 'lal mirch powder 200gms', 'lal mirch powder 500gms'],
    'red chilli sauce' : ['red chilli sauce', 'red chilli sauce 200gm pet bottle 48X200gm', 'hot chili sauce'],
    'sriraja hot chilli sauce' : ['sriraja hot chilli sauce', 'sriracha hot chilli sauce'],
    'mineral water' : ['himalayan orchard pure peach flavoured natural mineral water - 500 ml','himalayan orchard pure strawberry flavoured natural mineral water - 500 ml','himalayan orchard pure apple flavoured natural mineral water - 500 ml','himalayan - the natural mineral water - 500ml bottle', 'himalayan - the natural mineral water - 200ml bottle', 'himalayan - the natural mineral water - 1ltr bottle'],
}

для каждого ключа в словаре мы перебираем его значение списка. Если какое-либо значение в списке соответствует ИМЯ ПУНКТА в фрейме данных pandas, оно должно вывести как фрейм данных, так и значение списка в словаре. Он отлично работает, когда происходит совпадение. Кроме того, он печатает пустой фрейм данных, когда нет соответствия. Я хочу предотвратить это. Если совпадений нет, нет необходимости хранить пустую строку в кадре данных df1.

df = pd.read_csv('toy_data.csv', engine='python')
#print(df)
for x in smer_prods:
    list_smer = smer_prods[x]
    #print(list_smer)
    for y in list_smer:
        mask = df['ITEM NAME'] == y
        df1 = df[mask]
        print('-'*80)
        print(df1)
        print('-'*80)
        print(list_smer)

Вывод:

--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['vermicelli jupiter']
--------------------------------------------------------------------------------
   S.NO                 ITEM NAME
1     2  sriraja hot chilli sauce
--------------------------------------------------------------------------------
['sriraja hot chilli sauce', 'sriracha hot chilli sauce']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['sriraja hot chilli sauce', 'sriracha hot chilli sauce']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['himalayan orchard pure peach flavoured natural mineral water - 500 ml', 'himalayan orchard pure strawberry flavoured natural mineral water - 500 ml', 'himalayan orchard pure apple flavoured natural mineral water - 500 ml', 'himalayan - the natural mineral water - 500ml bottle', 'himalayan - the natural mineral water - 200ml bottle', 'himalayan - the natural mineral water - 1ltr bottle']
--------------------------------------------------------------------------------
   S.NO                                          ITEM NAME
8     9  himalayan orchard pure strawberry flavoured na...
--------------------------------------------------------------------------------
['himalayan orchard pure peach flavoured natural mineral water - 500 ml', 'himalayan orchard pure strawberry flavoured natural mineral water - 500 ml', 'himalayan orchard pure apple flavoured natural mineral water - 500 ml', 'himalayan - the natural mineral water - 500ml bottle', 'himalayan - the natural mineral water - 200ml bottle', 'himalayan - the natural mineral water - 1ltr bottle']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['himalayan orchard pure peach flavoured natural mineral water - 500 ml', 'himalayan orchard pure strawberry flavoured natural mineral water - 500 ml', 'himalayan orchard pure apple flavoured natural mineral water - 500 ml', 'himalayan - the natural mineral water - 500ml bottle', 'himalayan - the natural mineral water - 200ml bottle', 'himalayan - the natural mineral water - 1ltr bottle']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['himalayan orchard pure peach flavoured natural mineral water - 500 ml', 'himalayan orchard pure strawberry flavoured natural mineral water - 500 ml', 'himalayan orchard pure apple flavoured natural mineral water - 500 ml', 'himalayan - the natural mineral water - 500ml bottle', 'himalayan - the natural mineral water - 200ml bottle', 'himalayan - the natural mineral water - 1ltr bottle']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['himalayan orchard pure peach flavoured natural mineral water - 500 ml', 'himalayan orchard pure strawberry flavoured natural mineral water - 500 ml', 'himalayan orchard pure apple flavoured natural mineral water - 500 ml', 'himalayan - the natural mineral water - 500ml bottle', 'himalayan - the natural mineral water - 200ml bottle', 'himalayan - the natural mineral water - 1ltr bottle']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['himalayan orchard pure peach flavoured natural mineral water - 500 ml', 'himalayan orchard pure strawberry flavoured natural mineral water - 500 ml', 'himalayan orchard pure apple flavoured natural mineral water - 500 ml', 'himalayan - the natural mineral water - 500ml bottle', 'himalayan - the natural mineral water - 200ml bottle', 'himalayan - the natural mineral water - 1ltr bottle']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['vermicelli upma']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['roasted vermicelli']
--------------------------------------------------------------------------------
   S.NO        ITEM NAME
4     5  rice vermicelli
--------------------------------------------------------------------------------
['rice vermicelli']
--------------------------------------------------------------------------------
   S.NO               ITEM NAME
0     1  finosta vermicelli-5kg
--------------------------------------------------------------------------------
['finosta vermicelli-5kg']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['red chilli sauce', 'red chilli sauce 200gm pet bottle 48X200gm', 'hot chili sauce']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['red chilli sauce', 'red chilli sauce 200gm pet bottle 48X200gm', 'hot chili sauce']
--------------------------------------------------------------------------------
   S.NO        ITEM NAME
2     3  hot chili sauce
--------------------------------------------------------------------------------
['red chilli sauce', 'red chilli sauce 200gm pet bottle 48X200gm', 'hot chili sauce']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['lemon & tamarind vermicelli']
--------------------------------------------------------------------------------
Empty DataFrame
Columns: [S.NO, ITEM NAME]
Index: []
--------------------------------------------------------------------------------
['red chilli (lal mirch)', 'guntur red chilli', 'red chilly whole(lal mirch)', 'red chilly wg', 'red chilli whole (hot) 1 kg', 'red chilli whole (rich colour) 1 kg']
--------------------------------------------------------------------------------
   S.NO          ITEM NAME
3     4  guntur red chilli
--------------------------------------------------------------------------------
['red chilli (lal mirch)', 'guntur red chilli', 'red chilly whole(lal mirch)', 'red chilly wg', 'red chilli whole (hot) 1 kg', 'red chilli whole (rich colour) 1 kg']
------------------------------------------------------------------------------

csv для pandas dataframe выглядит следующим образом: введите описание изображения здесь

    
1
  1. "Кроме того, он печатает пустой фрейм данных, когда нет совпадений. Я хочу предотвратить это." .. Каков ожидаемый выходной результат ..?
    2019-03-18 11: 20: 39Z
  2. Когда совпадений нет, ничего печатать не нужно.
    2019-03-18 11: 21: 13Z
  3. проверьте, что длина df1 не равна 0, тогда выведите еще, не .......
    2019-03-18 11: 22: 44Z
  4. Извините, я не правильно указал. Если совпадений нет, нет необходимости хранить пустую строку в кадре данных df1. Я редактировал вопрос.
    2019-03-18 11: 26: 14Z
1 ответ                              1                         

используйте .any ()

for x in smer_prods:
    list_smer = smer_prods[x]
    #print(list_smer)
    for y in list_smer:
        mask = df['ITEM NAME'] == y
        if mask.any() == True:
            df1 = df[mask]
            print('-'*80)
            print(df1)
            print('-'*80)
            print(list_smer)

Пример: р>

mask = [False, True, False]
print(any(mask))

mask = [False, False, False]
print(any(mask))

выход: р>

True
False
    
1
2019-03-18 11: 30: 43Z
источник размещен Вот