I'm new to Python. I have scraped a html table by pandas and I'm looking for ways to insert a new column with repeated string value and set it as the index of the table (as follow:). Reminded that the table is a long one :).
Original df:
Age IQ
12 100
15 111
. .
. .
. .
. .
13 121
Expected df"
Group Age IQ
A 12 100
A 15 111
. . .
. . .
. . .
. . .
A 13 121
We can use a Python dictionary to add a new column in pandas DataFrame. Use an existing column as the key values and their respective values will be the values for new column. import pandas as pd data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
Assign Multiple Values to a Column in Pandas Say you wanted to assign specific values to a new column, you can pass in a list of values directly into a new column. Some important things to note here: The order matters – the order of the items in your list will match the index of the dataframe, and
Pandas DataFrame consists of three principal components, the data, rows, and columns. Column in DataFrame : In Order to pick a column in Pandas DataFrame, we will either access the columns by calling them by their columns name.
Split String Columns in Pandas Similar to joining two string columns, a string column can also be split. If we wanted to split the Name column into two columns we can use the str.split () function and assign the result to two columns directly. We can do this by writing:
Use assign
to create a copy of your dataframe with a new column included:
df.assign(Group='A')
Age IQ Group
0 12 100 A
1 15 111 A
2 13 121 A
You can realign the columns afterwards
df.assign(Group='A')[['Group'] + df.columns.tolist()]
Group Age IQ
0 A 12 100
1 A 15 111
2 A 13 121
However, you can edit the dataframe in place with insert
. This has the added bonus of allowing you to specify where the new column goes.
df.insert(0, 'Group', 'A')
df
Group Age IQ
0 A 12 100
1 A 15 111
2 A 13 121
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With