how to create a pandas dataframe and set column 'date' in python

To create a pandas dataframe and set column 'date', you can use the pd.DataFrame() constructor followed by .assign() method to create a new column named 'date'. Here's an example:

main.py
import pandas as pd

# Create a dictionary of data
data = {'name': ['Alice', 'Bob', 'Charlie', 'David'],
        'age': [25, 30, 45, 35],
        'gender': ['F', 'M', 'M', 'M']}

# Create a pandas DataFrame from the dictionary
df = pd.DataFrame(data)

# Add a date column to the DataFrame
df = df.assign(date=['2021-10-01', '2021-10-02', '2021-10-03', '2021-10-04'])

print(df)
378 chars
15 lines

This will output the following DataFrame:

main.py
       name  age gender        date
0     Alice   25      F  2021-10-01
1       Bob   30      M  2021-10-02
2   Charlie   45      M  2021-10-03
3     David   35      M  2021-10-04
180 chars
6 lines

related categories

gistlibby LogSnag