Home > Enterprise >  from a list of dictionary values , want to create dataframe such that first value becomes column and
from a list of dictionary values , want to create dataframe such that first value becomes column and

Time:09-05

[{'category': 'A', 'maxvalue': '6', 'minvalue': '0'}, {'category': 'B', 'maxvalue': '11', 'minvalue': '6'}, {'category': 'C', 'maxvalue': '21', 'minvalue': '11'}, {'category': 'D', 'maxvalue': '31', 'minvalue': '21'}, {'category': 'E', 'maxvalue': '41', 'minvalue': '31'}, {'category': 'F', 'maxvalue': '9999999999', 'minvalue': '41'}]

DataFrame I want is of below format

A      B     C     D       E       F
0-6   6-11  11-21  21-31  31-41  41-51

CodePudding user response:

You need to reformat your data into a dictionary of column names and values e.g.

data = [{'category': 'A', 'maxvalue': '6', 'minvalue': '0'}, {'category': 'B', 'maxvalue': '11', 'minvalue': '6'}, {'category': 'C', 'maxvalue': '21', 'minvalue': '11'}, {'category': 'D', 'maxvalue': '31', 'minvalue': '21'}, {'category': 'E', 'maxvalue': '41', 'minvalue': '31'}, {'category': 'F', 'maxvalue': '9999999999', 'minvalue': '41'}]

values = { d['category'] : [f"{d['minvalue']}-{d['maxvalue']}"] for d in data }
df = pd.DataFrame(values)
print(df)

Output:

     A     B      C      D      E              F
0  0-6  6-11  11-21  21-31  31-41  41-9999999999

CodePudding user response:

L = [{'category': 'A', 'maxvalue': '6', 'minvalue': '0'}, {'category': 'B', 'maxvalue': '11', 'minvalue': '6'}, {'category': 'C', 'maxvalue': '21', 'minvalue': '11'}, {'category': 'D', 'maxvalue': '31', 'minvalue': '21'}, {'category': 'E', 'maxvalue': '41', 'minvalue': '31'}, {'category': 'F', 'maxvalue': '9999999999', 'minvalue': '41'}]
df = pd.DataFrame()
for i in reversed(L):
    df.insert(0, i.get("category"), [i.get("minvalue") '-' i.get("maxvalue")]) 

Output:

     A   B        C      D        E      F
0   0-6 6-11    11-21   21-31   31-41   41-9999999999
  • Related