【问题标题】:Iteration over a Pandas dataframe using a List Comprehension使用列表理解对 Pandas 数据帧进行迭代
【发布时间】:2013-08-22 19:26:31
【问题描述】:

我可以用另一种方式解决这个问题;但是,我有兴趣确切了解为什么尝试使用列表理解来迭代 pandas DataFrame 不起作用。 (这里a是一个Dataframe)

def func(a,seed1,seed2):
    for i in range(0,3):
        # Sum of squares. Results in a series containing 'date' and 'num' 
        sorted1 = ((a-seed1)**2).sum(1)
        sorted2 = ((a-seed2)**2).sum(1)

        # This makes a list out of the dataframe. 
        a = [a.ix[i] for i in a.index if sorted1[i]<sorted2[i]]
        b = [a.ix[i] for i in a.index if sorted1[i]>=sorted2[i]]
        # The above line throws the exception:
        # TypeError: 'builtin_function_or_method' object is not iterable

        # Throw it back into a dataframe...

        a = pd.DataFrame(a,columns=['A','B','C'])
        b = pd.DataFrame(b,columns=['A','B','C'])

        # Update the seed.
        seed1 = a.mean()
        seed2 = b.mean()

        print a.head()
        print "I'm computing."

【问题讨论】:

  • 你能添加完整的回溯以及什么是seed1和seed2吗?
  • @ViktorKerkez 使用三行随机数据帧,您会看到上述错误(seed1/2 已在上面定义),但 OP 的错误更多是 python 而不是 pandas。 :)
  • 我关注的是错误的事情 :) 我看到它们是作为参数传入的,但它们可以是任何东西......标量,DataFrames,猴鸟......无论如何,你的答案是正确。
  • @ViktorKerkez 哈!你说得对,他们可能是!我只是立即输入数字,看看会发生什么:)
  • 在向 pandas 提交 PR 之前,我经常使用猴鸟进行测试 :)

标签: python pandas dataframe


【解决方案1】:

问题是在第一行之后,a不再是DataFrame了:

a = [a.ix[i] for i in a.index if sorted1[i]<sorted2[i]]
b = [a.ix[i] for i in a.index if sorted1[i]>=sorted2[i]]

这是一个列表,因此没有索引属性(因此出错)。

一个python技巧是在一行中做到这一点(同时定义它们),即:

a, b = [a.ix[i] for ...], [a.ix[i] for ...]

也许更好的选择是在这里使用不同的变量名(例如 df)。

就像你说的,在 pandas 中有更好的方法来做到这一点,最明显的一种是使用掩码:

msk = sorted1 < sorted2

seed1 = df[msk].mean()
seed2 = df[~msk].mean()

【讨论】:

  • 是的,它是一个列表。但我的观点是,有人会认为:这里我们正在构建列表,通过访问数据帧中的值......这应该没问题(?)......但不是。
  • @MicheleReilly 但第一个列表理解很好。这是第二个绊倒(因为a 不再是原来的DataFrame)。
猜你喜欢
  • 2020-10-11
  • 1970-01-01
  • 2022-09-29
  • 2022-12-17
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 2017-03-08
  • 1970-01-01
相关资源
最近更新 更多