xxxxxxxxxx
import pandas as pd
# Assuming you have a DataFrame called 'df'
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# Convert DataFrame to dictionary
dictionary = df.to_dict()
print(dictionary)
xxxxxxxxxx
#Lazy way to convert json dict to df
pd.DataFrame.from_dict(data, orient='index').T
xxxxxxxxxx
import pandas as pd
my_dict = {key:value,key:value,key:value, }
df = pd.DataFrame(list(my_dict.items()),columns = ['column1','column2'])
xxxxxxxxxx
>>> df.to_dict('records')
[{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]
xxxxxxxxxx
import pandas as pd
# Create a list of dictionaries with new data
list_of_dictionary = [
{"date": "2019-11-03", "small_sold": 10376832, "large_sold": 7835071},
{"date": "2019-11-10", "small_sold": 10717154, "large_sold": 8561348},
]
# Create a dictionary of lists with new data
dict_of_list = {
"date": ["2019-11-17", "2019-12-01"],
"small_sold": [10859987, 9291631],
"large_sold": [7674135, 6238096]
}
# Convert list into DataFrame
avocados_df1 = pd.DataFrame(list_of_dictionary)
avocados_df2 = pd.DataFrame(dict_of_list)
xxxxxxxxxx
#orientstr {‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’}
#Determines the type of the values of the dictionary.
#‘dict’ (default) : dict like {column -> {index -> value}}
#‘list’ : dict like {column -> [values]}
#‘series’ : dict like {column -> Series(values)}
#‘split’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}
#‘records’ : list like [{column -> value}, … , {column -> value}]
#‘index’ : dict like {index -> {column -> value}}
# Example:
data = pandas.read_csv("data/data_name.csv")
to_dict = data.to_dict(orient="records")