【问题标题】:IndexingError when filtering a df [duplicate]过滤df时出现IndexingError [重复]
【发布时间】:2020-12-21 14:47:55
【问题描述】:

我正在尝试通过在如下行中选择不同的值来过滤数据框:

booleans = []

for result in dfcolumn:
    if re.search('1/1', result):
        booleans.append(True)
    else:
        booleans.append(False)
print(booleans[0:5])
print(len(booleans))

Filtered=pd.Series(booleans)
df2=df[Filtered]
df2

但是,每次我尝试这个我都会收到这个错误:

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

谁能帮我解决这个问题?

【问题讨论】:

标签: python pandas dataframe jupyter-notebook python-re


【解决方案1】:

试试这样的:

filtered = pd.Series([True, False, True], index=df.index)

所以...

filtered = pd.Series(booleans, index=df.index)

【讨论】:

  • 非常感谢 :) 那是做什么的?我对 python 有点陌生...
  • 熊猫系列有一个行索引,就像 DataFrames 一样。有了这个,我使用你的 df 的索引创建了系列。 pandas 需要对齐两个对象的索引以执行过滤(也适用于其他操作,如 concat 等)。如果 Series 和 df 都有标准数字索引,这应该始终有效。那么也许你的 df 有不同的索引?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-15
  • 2021-11-02
  • 1970-01-01
  • 2019-10-24
  • 2020-11-28
  • 1970-01-01
相关资源
最近更新 更多