python 列表中 pandas 数据框的问题

标签 python pandas

我有一个 Pandas 数据框,其中每一行都是一个列表。

我想搜索一个值,但出现错误。我知道我的值(value)存在。

我检查一下:

df["text list"][1] == ['رهبری']

得到:

True

那么我需要这个:

df[df["text list"] == ['رهبری']]

并收到此错误:

    ValueError                                Traceback (most recent call last)
    <ipython-input-42-f14f1b2306ec> in <module>
    ----> 1 df[df["text list"] == ['رهبری']]

    ~/.local/lib/python3.6/site-packages/pandas/core/ops/__init__.py in wrapper(self, other, axis)
       1205             # as it will broadcast
       1206             if other.ndim != 0 and len(self) != len(other):
    -> 1207                 raise ValueError("Lengths must match to compare")
       1208 
       1209             res_values = na_op(self.values, np.asarray(other))

    ValueError: Lengths must match to compare

最佳答案

当您将列表直接传递到 DataFrame 进行比较时,它需要具有相同大小的数组来进行元素明智的比较。

为了避免这种情况,我们可以使用 apply 来检查每一行是否存在列表:

# example dataframe
>>> df = pd.DataFrame({'text list':[['aaa'], ['bbb'], ['ccc']]})
>>> df
  text list
0     [aaa]
1     [bbb]
2     [ccc]

使用Series.apply检查[bbb]:

>>> m = df['text list'].apply(lambda x: x == ['bbb'])
>>> df[m]
  text list
1     [bbb]
<小时/>

因为我们使用的是apply,它基本上是后台的“循环”实现。我们可以避免使用 pandas 的开销并使用列表理解:

>>> m = [x == ['bbb'] for x in df['text list']]
>>> df[m]
  text list
1     [bbb]

关于python 列表中 pandas 数据框的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59628221/

相关文章:

python - 计算唯一 Python 数组区域之间的距离?

python - Pandas :使用 read_csv 解析不同列中的日期

python - 如何根据节点颜色向networkx图添加图例

python - Pandas 数据框按多行分组

python - 标记化数据时出错。 C 错误 : EOF following escape character

python - pandas中的Pandas时间序列分析

python - 在 Python exe 中调用子进程脚本的最佳方法

python - 使用字典值更新查询集

python - 查找后跟连字符或空格,后跟一个或多个全大写字母和数字的单词

python - 将二维 numpy 数组转换为数据帧行