简体   繁体   中英

Create a list of lists, List as look up table

I need to create list of lists according to the result from a list as a look up table

List

lists=['a','b','c']

Data

[
  {'rank': 1, 'keyword_name': 'keyword1', 'volume': None, 'asin': 'a'},
  {'rank': 30, 'keyword_name': 'keyword2', 'volume': None, 'asin': 'b'}
  {'rank': 4, 'keyword_name': 'keyword3', 'volume': 123, 'asin': 'c'}

  {'rank': 5, 'keyword_name': 'keyword3', 'volume': None, 'asin': 'c'}
]

so the new list of lists would be

// format of result

keyword_name|volume|rank


result = [
    ['keyword1',None,1],
    ['keyword2',None,30],
    ['keyword3',123,4],
    ['keyword3',None,5]
]

My initial code in mind is like below

results = []
for list in lists:
    for res in data:
        if res['asin'] == list:
           results.append(res)

But we all know it will not work.I need the result to put as data to pandas dataframe, But I have no idea how to achieve it

 import pandas as pd


 df = pd.DataFrame(data=results, columns=lists)

Why don't you simply use pd.DataFrame.from_records(data)

data = [
  {'rank': 1, 'keyword_name': 'keyword1', 'volume': None, 'asin': 'a'},
  {'rank': 30, 'keyword_name': 'keyword2', 'volume': None, 'asin': 'b'},
  {'rank': 4, 'keyword_name': 'keyword3', 'volume': 123, 'asin': 'c'},
  {'rank': 5, 'keyword_name': 'keyword3', 'volume': None, 'asin': 'c'}
]

df = pd.DataFrame.from_records(data)

甚至简单地说:

df = pd.Dataframe(data)

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