Example of how to add a column to a pandas DataFrame in python:
Create a simple dataframe with pandas
Let's start by creating a simple dataframe df:
>>> import pandas as pd>>> import numpy as np>>> data = np.arange(1,13)>>> data = data.reshape(3,4)>>> df = pd.DataFrame(data=data,columns=['a','b','c','d'])>>> dfa b c d0 1 2 3 41 5 6 7 82 9 10 11 12
Add a column to a dataframe dataframe
To add a column we can simply do like this:
>>> df['e'] = [30,40,50]>>> dfa b c d e0 1 2 3 4 301 5 6 7 8 402 9 10 11 12 50
or other option use the function concat():
>>> df_new_column = pd.DataFrame([[60],[70],[80]], columns=['f'] )>>> df_new_columnf0 601 702 80>>> df = pd.concat([df,df_new_column], axis=1)>>> dfa b c d f0 1 2 3 4 601 5 6 7 8 702 9 10 11 12 80
References
| Links | Site |
|---|---|
| concat() | pandas.pydata.org |
| Pandas : How to create an empty DataFrame and append rows & columns to it in python | thispointer.com |
| Add one row to pandas DataFrame | stackoverflow |
| Adding new column to existing DataFrame in Pandas | stackoverflow |
