DekGenius.com
PYTHON
Convert list of dictionaries to a pandas DataFrame
import pandas as pd
your_list = [{'points': 50, 'time': '5:00', 'year': 2010},
{'points': 25, 'time': '6:00', 'month': "february"},
{'points':90, 'time': '9:00', 'month': 'january'},
{'points_h1':20, 'month': 'june'}]
df = pd.DataFrame(your_list)
dataframe to list of dicts
df = pd.DataFrame({'Name': ['John', 'Sara','Peter','Cecilia'],
'Age': [38, 47,63,28],
'City':['Boston', 'Charlotte','London','Memphis']})
datadict = df.to_dict('records')
list of dict to dataframe
Supposing d is your list of dicts, simply:
import pandas as pd
df = pd.DataFrame(d)
python list of dict to dataframe
# Supposing d is your list of dicts, simply
df = pd.DataFrame(d)
# Note: this does not work with nested data
pandas df to list of dictionaries
In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
{'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
{'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]
list of dict to df
df = pd.DataFrame(d) #here d is list of dict
Converting Dataframe from list Using a list in the dictionary
# import pandas as pd
import pandas as pd
# list of name, degree, score
n = ["apple", "grape", "orange", "mango"]
col = ["red", "green", "orange", "yellow"]
val = [44, 33, 22, 11]
# dictionary of lists
dict = {'fruit': n, 'color': col, 'value': val}
df = pd.DataFrame(dict)
print(df)
pandas to list of dicts
In [20]: timeit df.T.to_dict().values()
1000 loops, best of 3: 395 µs per loop
In [21]: timeit df.to_dict('records')
10000 loops, best of 3: 53 µs per loop
Convert list of dictionaries to a pandas DataFrame
np.random.seed(0)
data = pd.DataFrame(
np.random.choice(10, (3, 4)), columns=list('ABCD')).to_dict('r')
print(data)
[{'A': 5, 'B': 0, 'C': 3, 'D': 3},
{'A': 7, 'B': 9, 'C': 3, 'D': 5},
{'A': 2, 'B': 4, 'C': 7, 'D': 6}]
© 2022 Copyright:
DekGenius.com