如何将具有重复值的新列插入到 Pandas 表中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44657226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert a new column with repeated values into a pandas table?
提问by JAY.Y
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 :).
我是 Python 的新手。我已经通过 Pandas 抓取了一个 html 表,我正在寻找方法来插入一个具有重复字符串值的新列并将其设置为表的索引(如下所示:)。提醒一下,桌子很长:)。
Original df:
原始 df:
Age IQ
12 100
15 111
. .
. .
. .
. .
13 121
Expected df"
预期 df"
Group Age IQ
A 12 100
A 15 111
. . .
. . .
. . .
. . .
A 13 121
回答by piRSquared
Use assign
to create a copy of your dataframe with a new column included:
使用assign
创建您的数据帧的副本,包括新的列:
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.
但是,您可以使用insert
. 这有一个额外的好处,即允许您指定新列的位置。
df.insert(0, 'Group', 'A')
df
Group Age IQ
0 A 12 100
1 A 15 111
2 A 13 121