gpt4 book ai didi

python - Pandas - 随机用其他行替换 10% 的行

转载 作者:行者123 更新时间:2023-12-01 01:57:35 33 4
gpt4 key购买 nike

我想随机选择 df 中所有行的 10%,并将每一行替换为 df 中随机采样的现有行。

随机选择 10% 的行 rows_to_change = df.sample(frac=0.1) 可以,我可以使用 replacement_sample = df.sample(n=1) 获得一个新的随机现有行) 但我如何将它们组合在一起以快速迭代整个 10%?

df 包含数百万行 x 约 100 列。

示例 df:

df = pd.DataFrame({'A':[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],'B':[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],'C':[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]})

A B C
0 1 1 1
1 2 2 2
2 3 3 3
3 4 4 4
4 5 5 5
5 6 6 6
6 7 7 7
7 8 8 8
8 9 9 9
9 10 10 10
10 11 11 11
11 12 12 12
12 13 13 13
13 14 14 14
14 15 15 15

假设它随机采样索引 2,13 以替换为随机选择的索引 6,9,最终 df 如下所示:

    A   B   C
0 1 1 1
1 2 2 2
2 7 7 7
3 4 4 4
4 5 5 5
5 6 6 6
6 7 7 7
7 8 8 8
8 9 9 9
9 10 10 10
10 11 11 11
11 12 12 12
12 13 13 13
13 10 10 10
14 15 15 15

最佳答案

您可以抽取一个随机样本,然后抽取另一个相同大小的随机样本,并将这些索引处的值替换为原始样本。

import pandas as pd

df = pd.DataFrame({'A': range(1,15), 'B': range(1,15), 'C': range(1,15)})

samp = df.sample(frac=0.1)
samp
# returns:
A B C
6 7 7 7
9 10 10 10

replace = df.loc[~df.index.isin(samp.index)].sample(samp.shape[0])
replace
# returns:
A B C
3 4 4 4
7 8 8 8

df.loc[replace.index] = samp.values

这会复制行而不进行替换

df
# returns:
A B C
0 1 1 1
1 2 2 2
2 3 3 3
3 7 7 7
4 5 5 5
5 6 6 6
6 7 7 7
7 10 10 10
8 9 9 9
9 10 10 10
10 11 11 11
11 12 12 12
12 13 13 13
13 14 14 14
14 15 15 15

要进行替换采样,请在定义 samp 时使用关键字 replace = True

关于python - Pandas - 随机用其他行替换 10% 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49991386/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com