[英]How to add a new column into an existing DataFrame?
I am trying to add a synthetic data column to the existing the movies dataset.我正在尝试将合成数据列添加到现有的电影数据集中。 This new column is the gross revenue of an actor's second most recent movie.
这个新列是演员最近第二部电影的总收入。
For example:例如:
Movie![]() |
Actor![]() |
Revenue![]() |
New Column *![]() |
---|---|---|---|
A![]() |
Nic Cage![]() |
$7 ![]() |
$5 ![]() |
B![]() |
Nic Cage![]() |
$6 ![]() |
$4 ![]() |
C ![]() |
Nic Cage![]() |
$5 ![]() |
- ![]() |
D![]() |
Nic Cage![]() |
$4 ![]() |
- ![]() |
E![]() |
Al Pacino![]() |
$3 ![]() |
$1 ![]() |
F ![]() |
Al Pacino![]() |
$2 ![]() |
- ![]() |
G ![]() |
Al Pacino![]() |
$1 ![]() |
- ![]() |
What is the most efficient way to code this in python?在 python 中对此进行编码的最有效方法是什么?
Assuming the movies are sorted, use groupby.shift
假设电影已排序,请使用
groupby.shift
df['New Column'] = df.groupby('Actor')['Revenue'].shift(-2, fill_value='-')
Output: Output:
Movie Actor Revenue New Column
0 A Nic Cage $7 $5
1 B Nic Cage $6 $4
2 C Nic Cage $5 -
3 D Nic Cage $4 -
4 E Al Pacino $3 $1
5 F Al Pacino $2 -
6 G Al Pacino $1 -
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.