我是 Python 的新手。我已经通过 Pandas 抓取了一个 html 表,我正在寻找方法来插入一个具有重复字符串值的新列并将其设置为表的索引(如下:)。提醒说这张桌子很长:)。
原始df:
Age IQ
12 100
15 111
. .
. .
. .
. .
13 121
Run Code Online (Sandbox Code Playgroud)
预期 df"
Group Age IQ
A 12 100
A 15 111
. . .
. . .
. . .
. . .
A 13 121
Run Code Online (Sandbox Code Playgroud)
使用assign创建您的数据帧的副本,包括新的列:
df.assign(Group='A')
Age IQ Group
0 12 100 A
1 15 111 A
2 13 121 A
Run Code Online (Sandbox Code Playgroud)
之后您可以重新对齐列
df.assign(Group='A')[['Group'] + df.columns.tolist()]
Group Age IQ
0 A 12 100
1 A 15 111
2 A 13 121
Run Code Online (Sandbox Code Playgroud)
但是,您可以使用insert. 这有一个额外的好处,即允许您指定新列的位置。
df.insert(0, 'Group', 'A')
df
Group Age IQ
0 A 12 100
1 A 15 111
2 A 13 121
Run Code Online (Sandbox Code Playgroud)