Create an excel file using pandas in python:
#pandas #python #excel #dataframe
users = [{
'user_id': 1
}, {
'user_id': 2
}]
df = pandas.DataFrame(users, columns=['user_id'])
filename = 'users_info_%s.xlsx' % random.randint(0, 100)
writer = pandas.ExcelWriter(filename, engine='xlsxwriter')
df.to_excel(writer, sheet_name='user information')
#pandas #python #excel #dataframe
Data Analysis
Create a
dataframe
from dictionary in Pandas
:import pandas
data = [{'id': 1, 'name': 'alireza'}, {'id': 2, 'name': 'Mohsen'}]
# Creating a dataframe from a dictionary object
df = pandas.DataFrame(data)
Now if you print dataframe:
> df
id name
0 1 alireza
1 2 Mohsen
NOTE:
the first column is the index column.In order to turn it to a dictionary after your aggregation, analysis, etc just use
to_dict
like below:df.to_dict(orient='records')
[{'id': 1, 'name': 'alireza'}, {'id': 2, 'name': 'Mohsen'}]
You are right! We didn't do anything useful on records, but the goal is to tell you how to turn dataframe to a dictionary not more.
NOTE:
on older version of pandas you have to use outtype='records'
rather than orient='records'
.#python #pandas #to_dict #outtype #orient #dictionary #dataframe
How to sort data based on a column in
You can use
The above sample assumes that you have a data frame called
#python #pandas #dataframe #sort #inplace
Pandas
?You can use
sort_values
in order to sort data in a dataframe
:df.sort_values(['credit'], ascending=False, inplace=True)
The above sample assumes that you have a data frame called
df
and sort it based on user credit. The sort order is Descending
(ascending=False). and it sorts in place (You don't have to copy the result into a new dataframe).#python #pandas #dataframe #sort #inplace