【问题标题】:How to do columnwise operations in pandas?如何在熊猫中进行列操作?
【发布时间】:2018-08-22 03:37:33
【问题描述】:

我有一个看起来像这样的数据框:

 sample parameter1 parameter2 parameter3
 A      9           6         3        
 B      4           5         7
 C      1           5         8

我想做一个类似的操作:

for sample in dataframe:
    df['new parameter'] = df[sample, parameter1]/df[sample, parameter2]

到目前为止我已经尝试过:

df2.loc['ratio'] = df2.loc['reads mapped']/df2.loc['raw total sequences']

但我得到了错误:

KeyError: 'the label [reads mapped] is not in the [index]'

当我很清楚它在索引中时,所以我认为我在某处遗漏了一些概念。非常感谢任何帮助!

我应该补充一点,参数值是浮点数,以防万一这也是一个问题!

【问题讨论】:

  • 我想你只是想要df.parameter1.div(df.parameter2)
  • 我已经看到并尝试过了。它给我带来了很多错误,主要是我的索引在索引中不存在。我已经验证它确实存在于索引中,我认为这是因为“parameter1”不是字符串值?

标签: python pandas dataframe


【解决方案1】:

.loc 方法首先需要行索引,然后是列索引,因此以下应该可以工作,因为您想进行按列操作:

 df2['ratio'] = df2.loc[:, 'reads mapped'] / df2.loc[:, 'raw total sequences']

您可以在documentation 中找到更多信息。

【讨论】:

  • 这正是我要找的!知道为什么我会收到此错误吗? : 试图在 DataFrame 的切片副本上设置一个值。尝试改用 .loc[row_indexer,col_indexer] = value
  • 这是一个SettingWithCopyWarning,这意味着 df2 只是其他一些 DataFrame 的一部分。您可以通过将 .copy() 添加到代码中您首先从另一个 DataFrame 生成 df2 的任何位置来解决此问题。
  • @GAD 这对你有帮助吗?
  • 是的!添加 .copy() 允许我按照您期望的方式进行操作。非常感谢!
猜你喜欢
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多