我正在使用Pandas的DataFrames。合并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
答案 0 :(得分:1)
同意@bazingaa,只需使用:
fr.bucket[fr.item]
因此,使用命名为ipod
的字典键,然后像上面一样获取它的值。
答案 1 :(得分:0)
尝试一下:
# 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)
答案 2 :(得分:0)
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)#输出列表
答案 3 :(得分:0)
我尝试过,它有效
对于df.index中的i:
#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值(串联)转换为dict并提取了值