简体   繁体   English

如何在 pandas dataframe 中创建一个通过 dict 或 list 循环的列?

[英]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.然后我通过这个 dict 通过迭代发出 API 请求,每个请求都转换为 dataframe 并将结果存储在列表响应中。

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.我想向每个数据框添加额外的列“request_id”。

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但它总是为每个 dataframe 创建一个列,最后一个 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您可能需要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 . request_id将始终以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: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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