简体   繁体   English

列表的熊猫数据框的python问题

[英]python problem with pandas dataframe of list

I have a Pandas dataframe in which every row is a list.我有一个 Pandas 数据框,其中每一行都是一个列表。

I want to search a value, but I've got an error.我想搜索一个值,但出现错误。 and I know my value exists.我知道我的价值存在。

I check this:我检查这个:

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

and got:并得到:

True

then i need this:那我需要这个:

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

and got this error:并收到此错误:

    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

When you pass the list directly to your DataFrame for comparison, it expects an array with the same size to make an element wise comparison.当您将列表直接传递给 DataFrame 进行比较时,它需要一个具有相同大小的数组来进行元素明智的比较。

To avoid this, we can use apply to check on each row if the list is present:为了避免这种情况,我们可以使用apply来检查列表是否存在:

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

Use Series.apply to check for [bbb] :使用Series.apply检查[bbb]

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

Since we are using apply which is basically a "loopy" implementation in the background.由于我们使用的是apply ,它在后台基本上是一个“循环”的实现。 We can avoid using the overhead of pandas and use list comprehension:我们可以避免使用 Pandas 的开销并使用列表理解:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM