gpt4 book ai didi

python - 在 pandas 中对整个 DataFrame 进行采样时,避免连续列中出现两个相同的值

转载 作者:行者123 更新时间:2023-12-01 02:03:49 26 4
gpt4 key购买 nike

我想通过“pd.sample”方法随机化我的DataFrame,但为了实现条件采样。我需要结果满足以下条件:特定列中连续两行没有相同的值。

e.g.: A  B
a 2
b 3
c 3
d 4

我想要像这样的示例结果

e.g.  A  B
a 2
c 3
d 4
b 3

(即 B 包含相同值的行不会是连续的)

我怎样才能实现这个目标?我已经有以下内容,但作为新手,我不熟悉编写循环语句:

def compareSyllable(data):
for i in data:
(data['B'] != data['B'].shift()).any()

while compareSyllable(data) == True:
for i in range(data):
data_final=data.sample(frac=1)

最佳答案

比较音节

我会使用values属性来获取一个numpy数组。此比较的语法更清晰。 IIUC,您不希望在任何列中从一行到下一行有任何匹配值。因此,在 numpy 数组上使用 all 会自动检查数组中的每个值。

conditional_sample

我这样做是为了让您实际上可以通过 pd.DataFrame.pipe 将您想要的任何参数传递给 pd.DataFrame.sample。我还参数化了条件采样所依赖的谓词。这意味着,您可以创建其他条件函数来传递以满足其他目的。

pd.DataFrame.pipe

pipe 是一个 DataFrame 方法,其第一个参数是可调用的。 pipe 传递给该可调用函数作为其第一个参数,与调用 pipe 的 DataFrame 相同。其余参数将传递给可调用函数。

def compare_syllable(data):
v = data.values
return (v[:-1] != v[1:]).all()

def conditional_sample(df, predicate, *args, **kwargs):
d = df.sample(*args, **kwargs)
while not predicate(d):
d = df.sample(*args, **kwargs)
return d

df.pipe(conditional_sample, compare_syllable, frac=1)

A B
2 c 3
0 a 2
1 b 3
3 d 4
<小时/>

我还要指出 pipe 是我的选择,我们也可以通过像这样的更正常的方式来调用它:

conditional_sample(
df=df,
predicate=compare_syllable,
frac=1
)

A B
2 c 3
0 a 2
3 d 4
1 b 3
<小时/>

演示

为了进一步证明我们可以传递其他参数,我将放弃 frac=1 参数并传递 3,这将是要采样的行数

df.pipe(conditional_sample, compare_syllable, 3)

A B

1  b  3
0 a 2
3 d 4

这也满足条件。

<小时/>

包含无限循环处理的版本

from itertools import count, islice

def compare_syllable(data):
v = data.values
return (v[:-1] != v[1:]).all()

def conditional_sample(df, predicate, limit=None, **kwargs):
"""default limit of None is infinite limit"""
d = df.sample(**kwargs)
for i in islice(count(), limit):
if predicate(d):
return d
break
else:
d = df.sample(**kwargs)

df.pipe(conditional_sample, compare_syllable, limit=10, frac=1)

A B
2 c 3
3 d 4
1 b 3
0 a 2

关于python - 在 pandas 中对整个 DataFrame 进行采样时,避免连续列中出现两个相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49270242/

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