A data frame in Python is the data object that stores tabular information. It is provided by Pandas library. Once a data frame is generated, its value can be assigned or updated. For example, we can first set new column and row index labels, which is shown in the following code example.
#Import Pandas data frame
import pandas as pd
DF1 = pd.DataFrame(np.arange(12).reshape((4,3)),
index=['row1', 'row2', 'row3', 'row4'],
columns=['wilson', 'shirley', 'dudu'])
DF1
#output
wilson shirley dudu
row1 0 1 2
row2 3 4 5
row3 6 7 8
row4 9 10 11
#Set column and row index names
DF1.index.name = 'Rows';
DF1.columns.name = 'Members'
DF1
#output
Members wilson shirley dudu
Rows
row1 0 1 2
row2 3 4 5
row3 6 7 8
row4 9 10 11
If you want to add a new column to the existent data frame, you can just add column name inside the brackets after the data frame, then put the values, either a single value or a list or Series on the right side of the assignment symbol. Next examples show these operations.
#Assign a new column with same value for each row of this column
DF1['maomao'] = 8
DF1
#output
Members wilson shirley dudu maomao
Rows
row1 0 1 2 8
row2 3 4 5 8
row3 6 7 8 8
row4 9 10 11 8
#Or we can add a new column with values from a list
DF1['new1'] = [9,10,11,12]
DF1
#output
Members wilson shirley dudu maomao new1
Rows
row1 0 1 2 8 9
row2 3 4 5 8 10
row3 6 7 8 8 11
row4 9 10 11 8 12
#We can also create a Series, then assign it to the new column of data frame
S1 = pd.Series(np.arange(4))
S1
#output
0 0
1 1
2 2
3 3
dtype: int32
DF1['new2'] = S1
DF1
#output
Members wilson shirley dudu maomao new1 new2
Rows
row1 0 1 2 8 9 NaN
row2 3 4 5 8 10 NaN
row3 6 7 8 8 11 NaN
row4 9 10 11 8 12 NaN
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…