[英]Add elements from list to new data frame column based on condition
I have this dataframe:我有这个 dataframe:
id1 ![]() |
id2 ![]() |
---|---|
2341 ![]() |
qw123 ![]() |
2321 ![]() |
- ![]() |
- ![]() |
de121![]() |
2341 ![]() |
qd111 ![]() |
And I want to add 3rd column id3
with randomly generated ids in a list:我想在列表中添加带有随机生成的 id 的第三列
id3
:
['11231', '123141', '234512']
The thing that makes it difficult to me is how to attach the same random id from the list to each row where id1
is the same.让我感到困难的是如何将列表中的相同随机 id 附加到
id1
相同的每一行。
For example the output file should look like this:例如 output 文件应如下所示:
id1 ![]() |
id2 ![]() |
id3 ![]() |
---|---|---|
2341 ![]() |
qw123 ![]() |
11231 ![]() |
2321 ![]() |
- ![]() |
123141 ![]() |
- ![]() |
de121![]() |
234512 ![]() |
2341 ![]() |
qd111 ![]() |
11231 ![]() |
Any solution is appreciated!任何解决方案表示赞赏!
You can create a dict for mapping the unique id1
keys to the random numbers.您可以创建一个字典来将唯一的
id1
键映射到随机数。 Then use .map()
to map id1
values to these random numbers for assignment to new column id3
, as follows:然后使用
.map()
将 map id1
值分配给这些随机数以分配给新列id3
,如下所示:
num_list = ['11231', '123141', '234512']
id1_unique = df['id1'].unique()
m_dict = dict(zip(id1_unique, np.random.choice(num_list, len(id1_unique))))
df['id3'] = df['id1'].map(m_dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.