100 days of code: Day 42 - pandas

Last modified on 2020-07-21

Source: 100-days-of-code.

I want to be able to output graphs from my datetag program. This is how I discovered pandas, a Python module used in data analysis. Pandas doesn’t make graphs, but it can convert my dictionary of dates and measurements into a tabular data object suitable both for display onscreen and passing along to a graphing library.

I’m a bit hazy on the details. Time to create some code! Here I use dict_to_dataframe.py to convert a small dictionary to tabulated data using DataFrame()

import pandas as pd

my_dict = {'2015-01-29': '75.7', '2015-02-28': '69.6', '2015-03-27': '67.7', '2015-04-26': '60.3'}

# Convert dictionary to dataframe
df = pd.DataFrame(list(my_dict.items()),columns = ['Date','Measurement'])
print(df)
print()
print(df['Date'])
print()
print(df['Measurement'])

Run …

$ python3 dict_to_dataframe.py 
         Date Measurement
0  2015-01-29        75.7
1  2015-02-28        69.6
2  2015-03-27        67.7
3  2015-04-26        60.3

0    2015-01-29
1    2015-02-28
2    2015-03-27
3    2015-04-26
Name: Date, dtype: object

0    75.7
1    69.6
2    67.7
3    60.3
Name: Measurement, dtype: object

Happy hacking!