gpt4 book ai didi

python - 如何检查 pandas 数据框中的字符串值序列并输出后续内容

转载 作者:行者123 更新时间:2023-12-02 19:21:49 24 4
gpt4 key购买 nike

我正在尝试检查数据帧中 B-B-B 的顺序。

d = {'A': ['A','B','C','D','B','B','B','A','A','E','F','B','B','B','F','A','A']}
testdf = pd.DataFrame(data=d)

array = []
seq = pd.Series(['B', 'B', 'B'])

for i in testdf.index:

if testdf.A[i:len(seq)] == seq:

array.append(testdf.A[i:len(seq)+1])

我收到错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我怎样才能让它工作?我不明白这段代码有什么“不明确”之处

我想要的输出是:

A, F

最佳答案

  1. ambiguous比较来自这样一个事实:当您测试 2 Series 时为了相等(它们应该大小相同),进行一对比较,您将获得 SeriesTrue/False值,然后您应该使用 .any(), .all(), ... 决定是否想要全真、全假、至少一个真...

    s1 = pd.Series(['B', 'B', 'B'])
    s2 = pd.Series(['A', 'B', 'B'])

    print(s1 == s2)
    0 False
    1 True
    2 True
    dtype: bool

    print((s1 == s2).all())
    False
  2. 要访问子序列,最好使用 .iloc

  3. 您需要使用[i:i + len(seq)]而不是[i:len(seq)]因为这是一个[from:to]符号

  4. 您需要使用Series.reset_index(drop=True)因为要比较系列,它们必须具有相同的索引,例如 seq如果始终索引 0,1,2您计算的 sht 子序列也需要相同的内容(因为 testdf.A.iloc[1:3] 被索引 1,2,3 ]

  5. 在检查系列之前验证长度,以避免在子序列变小时结束时出现异常

你的结尾是:

values = {'A': ['A', 'B', 'C', 'D', 'B', 'B', 'B', 'A', 'A', 'E', 'F', 'B', 'B', 'B', 'F', 'A', 'A']}
testdf = pd.DataFrame(values)
array = []
seq = pd.Series(['B', 'B', 'B'])
for i in testdf.index:
test_seq = testdf.A.iloc[i:i + len(seq)].reset_index(drop=True)
if len(test_seq) == len(seq) and (test_seq == seq).all():
array.append(testdf['A'].iloc[i + len(seq)])
print(array) # ['A', 'F']

关于python - 如何检查 pandas 数据框中的字符串值序列并输出后续内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62959228/

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