Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a new column with repeated values into a pandas table? [duplicate]

Tags:

python

pandas

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
like image 742
yeungcase Avatar asked Jun 20 '17 15:06

yeungcase


People also ask

How to add a new column in pandas Dataframe?

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'],

How do I assign multiple values to a column in pandas?

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

What are the components of pandas Dataframe?

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.

How do I split a column into two columns in pandas?

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:


1 Answers

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
like image 191
piRSquared Avatar answered Nov 12 '22 08:11

piRSquared