【问题标题】:Python Function to use row numbers in a function [closed]Python函数在函数中使用行号[关闭]
【发布时间】:2021-11-12 17:34:24
【问题描述】:
df['New Column'][0] = chi2_contingency([[df['A'][0],df['B'][0]],[df['C'][0],df['D'][0]]])
df['New Column'][1] = chi2_contingency([[df['A'][1],df['B'][1]],[df['C'][1],df['D'][1]]])
df['New Column'][2] = chi2_contingency([[df['A'][2],df['B'][2]],[df['C'][2],df['D'][2]]])
df['New Column'][3] = chi2_contingency([[df['A'][3],df['B'][3]],[df['C'][3],df['D'][3]]])

各位,我该如何编写一个函数来替换上面的代码?我需要更新行号(范围是 0 - 50)?

【问题讨论】:

  • df['New column'] = df[['A','B','C','D']].apply(chi2_contingency, axis=1) 之类的东西(或者 chi2_contingency 需要接收每一行)可能更直接。

标签: python pandas loops for-loop


【解决方案1】:

我觉得你是那个意思

for x in range(50):
    df['New Column'][x] = chi2_contingency([[df['A'][x],df['B'][x]],[df['C'][x],df['D'][x]]])

【讨论】:

  • 不过,这将是 很多 SettingWithCopyWarnings。
  • 是的,我有几个 SettingWithCopyWarnings。但除此之外,它工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 2015-09-26
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多