【问题标题】:apply a function to each row of the dataframe对数据框的每一行应用一个函数
【发布时间】:2018-10-29 11:28:27
【问题描述】:

下面有什么更优雅的实现方式?

我想将一个函数:my_function 应用于一个数据帧,其中数据帧的每一行都包含函数的参数。然后我想将函数的输出写回数据框行。

results = pd.DataFrame()
for row in input_panel.iterrows():
    (index, row_contents) = row
    row_contents['target']  = my_function(*list(row_contents))
    results = pd.concat([results, row_contents])

【问题讨论】:

标签: python pandas apply


【解决方案1】:

我们将遍历这些值并在最后构建一个 DataFrame。

results = pd.DataFrame([my_function(*x) for x in input_panel.values.tolist()])

不太推荐的方法是使用DataFrame.apply:

results = input_panel.apply(lambda x: my_function(*x))

apply 的唯一优点是打字少。

【讨论】:

  • 为什么不推荐申请?或者应用解决方案有错误:TypeError: ('my_function() 恰好需要 7 个参数(给定 13 个)', u'发生在索引偏差')
  • @Lisa 这比循环慢...有时人们喜欢少打字,只要他们完成工作,他们就不会关心速度。至于错误,你必须自己解决这个问题,因为你传递的参数比你想要的多,而你的问题并没有暗示这一点。没有您的数据,我无法提供更多建议。
猜你喜欢
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 2011-11-02
  • 2022-01-07
相关资源
最近更新 更多