1#using the insert function:
2df.insert(location, column_name, list_of_values)
3#example
4df.insert(0, 'new_column', ['a','b','c'])
5#explanation:
6#put "new_column" as first column of the dataframe
7#and puts 'a','b' and 'c' as values
8
9#using array-like access:
10df['new_column_name'] = value
11
12#df stands for dataframe
1# Basic syntax:
2pandas_dataframe['new_column_name'] = ['list', 'of', 'column', 'values']
3
4# Note, the list of column values must have length equal to the number
5# of rows in the pandas dataframe you are adding it to.
6
7# Add column in which all rows will be value:
8pandas_dataframe['new_column_name'] = value
9# Where value can be a string, an int, a float, and etc
1# pre 0.24
2feature_file_df['RESULT'] = RESULT_df['RESULT'].values
3# >= 0.24
4feature_file_df['RESULT'] = RESULT_df['RESULT'].to_numpy()
1# Import pandas package
2import pandas as pd
3
4# Define a dictionary containing Students data
5data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
6 'Height': [5.1, 6.2, 5.1, 5.2],
7 'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
8
9# Convert the dictionary into DataFrame
10df = pd.DataFrame(data)
11
12# Declare a list that is to be converted into a column
13address = ['Delhi', 'Bangalore', 'Chennai', 'Patna']
14
15# Using 'Address' as the column name
16# and equating it to the list
17df['Address'] = address
18
19# Observe the result
20df
1import pandas as pd
2
3data = {'Name': ['Josh', 'Stephen', 'Drake', 'Daniel'],
4 'Height': [5.5, 6.0, 5.3, 4.9]}
5
6'''
7printing data at this point will show the following
8 Name Height
90 Josh 5.1
101 Stephen 6.2
112 Drake 5.1
123 Daniel 5.2
13'''
14
15df.insert(2, "Age", [20, 21, 20, 19])
16
17'''
18printing data now will show the following
19
20 Name Height Age
210 Josh 5.1 20
221 Stephen 6.2 21
232 Drake 5.1 20
243 Daniel 5.2 19
25'''
26
27