简体   繁体   中英

Zipping two dataframe columns to dict getting TypeError: 'dict' object is not callable

Let's say I have a dataframe that looks like this:

    order               responses
1   [63, 61, 64, 62]    [3, 4, 4, 3]
2   [64, 61, 62, 63]    [1, 2, 3, 4]
3   [62, 64, 61, 63]    [3, 4, 4, 3]
4   [61, 63, 64, 62]    [4, 1, 4, 4]
5   [61, 63, 64, 62]    [4, 4, 2, 1]
6   [63, 64, 62, 61]    [4, 4, 4, 4]
7   [64, 61, 62, 63]    [3, 3, 3, 3]
8   [64, 62, 63, 61]    [4, 2, 4, 3]
9   [61, 62, 64, 63]    [3, 2, 4, 4]
10  [63, 62, 61, 64]    [4, 98, 3, 4]
11  [63, 62, 61, 64]    [4, 4, 4, 4]
12  [64, 62, 61, 63]    [4, 3, 4, 3]

My goal is to create a dictionary that holds {order: responses}

I have attempted to do this, by the following lines:

df['combo'] = df[['order', 'responses']].apply(lambda x: zip(x[0], x[1]), axis=1)

Which returns me a list of zip objects in column combo .

Now, when I try something of the following nature:

df['combo'] = df[['order', 'responses']].apply(lambda x: dict(zip(x[0], x[1])), axis=1)

it results in the following traceback:

TypeError: ("'dict' object is not callable", 'occurred at index 1')

When I try the following:

x = dict(zip(df.order,df.responses))

results in:

TypeError: 'dict' object is not callable

So, it is quite evident that I am not calling the dictionary object properly.

My Objective: I need to return some sort of data structure that holds all of these dictionaries.

I don't often post here, sorry if anything is out of line with guidelines. Thanks for your help!

dict will not accept the key as type of list , so we convert it to tuple

d=dict(zip(df.order.apply(tuple),df.responses))
d
Out[155]: {(63, 61, 64, 62): [3, 4, 4, 3], (64, 61, 62, 63): [1, 2, 3, 4]}

As pault methioned

[dict(zip(x,y))for x , y in zip (df.order,df.responses)]
Out[158]: [{61: 4, 62: 3, 63: 3, 64: 4}, {61: 2, 62: 3, 63: 4, 64: 1}]

The problem is here:

.apply(lambda x: dict(zip(x[0], x[1])), axis=1)

apply is a command to apply the given function -- your lambda -- to each element of the sequence before .apply . However, you defined your lambda as a dict, rather than a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM