简体   繁体   中英

How to create a column in pandas dataframe looping through dict or list?

There is a dict

dict_example = {

'Request_1': {
    'request_id' : '1',
    'name' : 'Foo'
},

'Request_2': {
    'request_id' : '2',
    'name' : 'Bar'

},

'Request_3': {
    'request_id' : '3',
    'name' : 'Barbie'
}

And then I make API requests via iteration through this dict, each request is converted to a dataframe and the result stored in a list responses.

API_request = get_me_api(
             for k,v in dict_example.items():
                 name=v['name'])

             responses.append(API_request)

responses = [df1, df2, df3]

df1

   age name city street
0   1   Foo  LA   street A

df2

   age name city street
0   10  Bar  NY   street B

df3

   age name   city street
0   20  Barbi  SF   street C

I want to add additional column 'request_id' to each of the dataframes.

I tried to make through an iteration

for v in yt_params.values():
               dict_example ['request_id'] = v['request_id']

# and just a list 

request_ids = [1,2,3]

for response in responses:
   for request in request_ids:
       response['request_id'] = request

But it creates a column for every dataframe always with the last request_id

df1

   age name city street    request_id
0   1   Foo  LA   street A           3

df2

   age name city street   request_id
0   10  Bar  NY   street B          3

df3

   age name   city street    request_id
0   20  Barbi  SF   street C          3

You probably need zip

Ex:

for response, id in zip(responses, request_ids):
    response['request_id'] = id

You made a mistake in your loops. request_id will always end up with the last entry in request_ids . Here is an example of what is happening:

letters = ["a", "b", "c"]
numbers = [1, 2, 3]
end_product = {}

for letter in letters:
    for number in numbers:
        end_product[letter] = number
        print(end_product)

Output:

{'a': 1}
{'a': 2}
{'a': 3}                  #Last iteration sets "a" to 3
{'a': 3, 'b': 1}
{'a': 3, 'b': 2}
{'a': 3, 'b': 3}          # Last iteration sets "b" to 3
{'a': 3, 'b': 3, 'c': 1}
{'a': 3, 'b': 3, 'c': 2}
{'a': 3, 'b': 3, 'c': 3}  # Last iteration sets "c" to 3

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