14

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
EdChum
  • 376,765
  • 198
  • 813
  • 562
yeungcase
  • 383
  • 2
  • 3
  • 12

1 Answers1

15

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
piRSquared
  • 285,575
  • 57
  • 475
  • 624