Строка в JSON Сравнить с использованием панд - PullRequest
0 голосов
/ 02 ноября 2018

Я использую DataFrames от Pandas. У меня есть такой случай после объединения 2 файлов: fr.item = "ipod"; fr.bucket = {'ipad':34,'ipod':36,'iwatch':27} Примечание: тип данных Series здесь

Есть ли способ проверить наличие элемента в корзине (ipod) и значения выборки (36) здесь? Кроме того, выполнение этого без цикла приветствуется, поскольку я выполняю сравнение столбца к столбцу.

Входы

item    bucket
ipod    {'ipad':34,'ipod':36,'iwatch':27}
ipad    {'ipad':87,'ipod':31,'iwatch':62}

выход

36
87

Ответы [ 4 ]

0 голосов
/ 05 ноября 2018

Я попробовал это, это сработало

для меня в df.index:

#For Bucket
val_bucket=ast.literal_eval(bucket[i])
for key, val in val_bucket.items():
    if my_items[i]== key:
        print ("Value",val)
         break

Итак, я преобразовал эти значения JSON (которые были в серии), чтобы продиктовать и извлечь значение

0 голосов
/ 02 ноября 2018

Попробуйте это:

# update col1 and col2 to the name of your item and bucket column
col1 = 'item'
col2 = 'bucket'
output = fr.apply(lambda row: row[col2][col1], axis=1)

Он вернет серию панд 36, 87.

Обновление: Если ваши элементы в столбце корзины имеют тип str, попробуйте сначала следующее:

import ast
fr.loc[:, col2] = fr[col2].apply(ast.literal_eval)
0 голосов
/ 04 ноября 2018
item=['ipod','ipad']
bucket=[{'ipad':34,'ipod':36,'iwatch':27},{'ipad':87,'ipod':31,'iwatch':62}]

result_output=[]    # Defining for output
counter=0           # For initialising the counter through the bucket's elements
for key in item:    # For each row value in column1. Column1 is item.
   temp_bucket=dict(bucket[counter]) # For each column's value,it is as a dictionary
   if key in temp_bucket:   # Checking if the column1's value is present in the dictionary of that row (column2)   
      length_1=len(bucket)-1                 # Need to subtract 1 as python is based on 0 indexing     
      result_output.append(temp_bucket[key]) # Appending each row output to the result list.
      if counter<length_1:                   # Need to check if there is sufficient element is present in column2. Otherwise throw error for index.
         counter=counter+1                  # for checking the next element of column2

print (result_output) # Список вывода

0 голосов
/ 02 ноября 2018

Согласитесь с @bazingaa, просто используйте:

fr.bucket[fr.item]

Итак, получите ключ словаря с именем ipod, затем получите его значение, как указано выше, вот и все.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...