【问题标题】:Isin function skip correct value pythonisin函数跳过正确值python
【发布时间】:2020-11-13 15:21:59
【问题描述】:

我正在处理来自 get API 请求的响应 json 文件。我已经能够弄清楚如何展平响应,并且我想通过包含 pdf 文件扩展名的记录过滤相关的数据帧,我将使用这些文件扩展名来检索感兴趣的文件。 这是代码:

from flatten_json import flatten
import requests
import pandas as pd
import re
payload= {"chamber_type":"committee","chamber":"dail","date_start":"2018-01-01", "date_end":"2018-12-31", "limit":"1000"}
test = requests.get("https://api.oireachtas.ie/v1/debates", params=payload)
text = test.content.decode("utf-8")
print(text)
test.json()
test1=flatten(test.json())
df = pd.Series(test1).to_frame()
df[["pdf"]] = df[df.index.isin(["uri_pdf"])]

即使应该给出肯定的结果,整个 df 也会返回 nan。

我尝试使用相同的表达式过滤索引,但结果为空 df。

isin 在哪里不工作?

【问题讨论】:

    标签: python python-3.x pandas filtering isin


    【解决方案1】:

    .isin() 不像你预期的那样工作(例如包含)。 IIUC,你需要 str.contains():

    df[df.index.str.contains('pdf_uri')]
    

    或者在你的情况下你可以使用 str.endswith()

    df[df.index.str.endswith('pdf_uri')]
    

    【讨论】:

    • 嗨,Danail,你试过检查它是否有效吗?就我而言,它没有。要么是因为“索引”没有定义,甚至当我像最初发布的那样迭代 df.index 时。
    • 如果你只做df[df['Index'].str.endswith("uri_pdf")],你会得到什么?正如我在您的输出中看到的那样,我确实输入了“索引”,列名大写 I
    • 索引实际上是数据帧的索引而不是列,这就是为什么输出是:文件“pandas_libs\index.pyx”,第 111 行,在 pandas._libs.index.IndexEngine.get_loc 文件中“ pandas_libs\index.pyx”,第 138 行,在 pandas._libs.index.IndexEngine.get_loc 文件“pandas_libs\hashtable_class_helper.pxi”,第 1619 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item 文件“pandas_libs\hashtable_class_helper.pxi” ,第 1627 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'Index'
    • 它绝对适合我。 df[df.index.str.contains('pdf_uri')]
    • 经过一些调整后,您的解决方案最终对我有用。不,我知道 Isin 使用精确匹配,str.contains 更适合在字符串中搜索位。
    猜你喜欢
    • 1970-01-01
    • 2019-05-12
    • 2022-11-14
    • 2014-07-28
    • 1970-01-01
    • 2018-10-22
    • 2014-03-01
    • 2019-05-24
    • 2023-02-08
    相关资源
    最近更新 更多