add a dataframe serie to a dictionnary in python

You can add a Pandas DataFrame series to a Python dictionary using the following code:

main.py
import pandas as pd

# Create a Pandas DataFrame with a single column
df = pd.DataFrame({'Column1': [1, 2, 3, 4, 5]})

# Create an empty Python dictionary
my_dict = {}

# Add the DataFrame column as a dictionary value with a key of your choice
my_dict['my_key'] = df['Column1']

# Print the dictionary
print(my_dict)
317 chars
14 lines

The output will be:

main.py
{'my_key': 0    1
1    2
2    3
3    4
4    5
Name: Column1, dtype: int64}
75 chars
7 lines

In this example, we created a Pandas DataFrame with a single column called Column1. Next, we created an empty Python dictionary called my_dict. We then added the DataFrame column df['Column1'] to the dictionary as a value, and chose my_key as the key. Finally, we printed the dictionary to show the result.

gistlibby LogSnag