gpt4 book ai didi

python - 在 pandas frozenset 中查找子字符串

转载 作者:行者123 更新时间:2023-11-28 22:11:49 24 4
gpt4 key购买 nike

我试图在 frozenset 中找到一个子字符串,但是我有点无能为力。

我的数据结构是一个 pandas.dataframe(它来自 mlxtend 包中的 association_rules,如果你熟悉的话)我想打印所有行其中前因(这是一个卡住集)包含一个特定的字符串。

示例数据: enter image description here

    print(rules[rules["antecedents"].str.contains('line', regex=False)])

但是,每当我运行它时,我都会得到一个空数据框。

当我尝试在我的 rules["antecedents"] 系列中只运行内部函数时,我得到的所有条目都只有 False 值。但这是为什么呢?

最佳答案

因为 dataframe.str.* 函数仅适用于字符串数据。由于您的数据不是字符串,因此无论其字符串表示形式如何,它始终为 NaN。证明:

>>> x = pd.DataFrame(np.random.randn(2, 5)).astype("object")
>>> x
0 1 2 3 4
0 -1.17191 -1.92926 -0.831576 -0.0814279 0.099612
1 -1.55183 -0.494855 1.14398 -1.72675 -0.0390948
>>> x[0].str.contains("-1")
0 NaN
1 NaN
Name: 0, dtype: float64

你能做什么:

使用应用:

>>> x[0].apply(lambda x: "-1" in str(x))
0 True
1 True
Name: 0, dtype: bool

所以你的代码应该这样写:

print(rules[rules["antecedents"].apply(lambda x: 'line' in str(x))])

如果你想在元素上精确匹配,你可能想使用 'line' in x

关于python - 在 pandas frozenset 中查找子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55402544/

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