man in gray sweatshirt sitting on chair in front of iMac

The way to Upload a Column to a Pandas DataFrame

Posted on
banner 336x280

You’ll be able to virtue the assign() serve as so as to add a unutilized column to the tip of a pandas DataFrame:

df = df.assign(col_name=[value1, value2, value3, ...])

And you’ll virtue the insert() serve as so as to add a unutilized column to a particular location in a pandas DataFrame:

banner 468x60
df.insert(place, 'col_name', [value1, value2, value3, ...])

Refer to examples display easy methods to virtue this syntax in apply with please see pandas DataFrame:

import pandas as pd

#develop DataFrame
df = pd.DataFrame({'issues': [25, 12, 15, 14, 19, 23],
                   'assists': [5, 7, 7, 9, 12, 9],
                   'rebounds': [11, 8, 10, 6, 6, 5]})

#view DataFrame
df

        issues	assists	rebounds
0	25	5	11
1	12	7	8
2	15	7	10
3	14	9	6
4	19	12	6
5	23	9	5

Instance 1: Upload Pristine Column to Finish of DataFrame

Refer to code presentations easy methods to upload a unutilized column to the tip of the DataFrame:

#upload 'steals' column to finish of DataFrame
df = df.assign(steals=[2, 2, 4, 7, 4, 1])

#view DataFrame
df

        issues	assists	rebounds steals
0	25	5	11	 2
1	12	7	8	 2
2	15	7	10	 4
3	14	9	6	 7
4	19	12	6	 4
5	23	9	5	 1

Instance 2: Upload A couple of Columns to Finish of DataFrame

Refer to code presentations easy methods to upload a couple of unutilized columns to the tip of the DataFrame:

#upload 'steals' and 'blocks' columns to finish of DataFrame
df = df.assign(steals=[2, 2, 4, 7, 4, 1],
               blocks=[0, 1, 1, 3, 2, 5])

#view DataFrame
df

	issues	assists	rebounds steals	blocks
0	25	5	11	 2	0
1	12	7	8	 2	1
2	15	7	10	 4	1
3	14	9	6	 7	3
4	19	12	6	 4	2
5	23	9	5	 1	5

Instance 3: Upload Pristine Column The usage of Current Column

Refer to code presentations easy methods to upload a unutilized column to the tip of the DataFrame, in response to the values in an current column:

#upload 'half_pts' to finish of DataFrame
df = df.assign(half_pts=lambda x: x.issues / 2)

#view DataFrame
df

        issues	assists	rebounds half_pts
0	25	5	11	 12.5
1	12	7	8	 6.0
2	15	7	10	 7.5
3	14	9	6	 7.0
4	19	12	6	 9.5
5	23	9	5	 11.5

Instance 4: Upload Pristine Column in Particular Location of DataFrame

Refer to code presentations easy methods to upload a unutilized column via putting it into a particular location within the DataFrame:

#upload 'steals' to column index place 2 in DataFrame
df.insert(2, 'steals', [2, 2, 4, 7, 4, 1])

#view DataFrame
df

        issues	assists	steals	rebounds
0	25	5	2	11
1	12	7	2	8
2	15	7	4	10
3	14	9	7	6
4	19	12	4	6
5	23	9	1	5

Extra Sources

The way to Exchange the Series of Columns in Pandas
The way to Rename Columns in Pandas
The way to Kind Columns via Identify in Pandas

banner 336x280

Leave a Reply

Your email address will not be published. Required fields are marked *