add variables to column pandas in python

To add a new column with variables to a pandas dataframe in Python, you can simply assign a list or numpy array of values to a new column name using the square bracket notation. Here's an example code snippet:

main.py
import pandas as pd

# create sample dataframe
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# create new column with variables
my_var = [10, 20, 30]
df['C'] = my_var

# print dataframe with new column
print(df)
219 chars
12 lines

In this code, we first create a new dataframe called df. Then, we define a variable my_var with a list of values. Finally, we create a new column in the dataframe called C and set its values to the my_var variable. We can then print the dataframe to see the new column has been added with the specified values.

gistlibby LogSnag