【问题标题】:Key error when dividind one row by another in Pandas在 Pandas 中将一行除以另一行时出现关键错误
【发布时间】:2021-10-06 08:46:35
【问题描述】:

我正在尝试对复杂的数据集执行一些计算,并努力寻找正确的方法。简单来说,我想做的是将一行中的值除以另一行中的值。我的意思示例如下;

Column A Values Column B
0 row 1 5 abc
1 row 2 10 def
2 row 3 15 ghi

我想要的输出是将第 1 行除以第 2 行,得到 0.5 或 50%,然后将此数据放入新行(第 4 行)。在这种情况下,我基本上想忽略 B 列和第 3 行。我仍然希望他们的数据在输出中,但他们不参与计算。输出应如下所示或类似。

Column A Values Column B
0 row 1 5 abc
1 row 2 10 def
2 row 3 15 ghi
3 row 4 0.5 NaN

这是一个简化的版本,因为我在现实中会有大量的行和列,但是概念是一样的。我想告诉 pandas 将哪两行进行除法、乘法等操作,然后放入新行。

这应该相当简单,使用我找到的以下代码;

df['row4']=df.loc[row 1]/df.loc[row.2]

但是这会在第 1 行返回一个关键错误

KeyError                                  Traceback (most recent call last)
<ipython-input-78-c216003d88c4> in <module>
----> 1 df['row4']=df.loc['row 1']/df.loc['row 2']

~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
    893 
    894             maybe_callable = com.apply_if_callable(key, self.obj)
--> 895             return self._getitem_axis(maybe_callable, axis=axis)
    896 
    897     def _is_scalar_access(self, key: Tuple):

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1122         # fall thru to straight lookup
   1123         self._validate_key(key, axis)
-> 1124         return self._get_label(key, axis=axis)
   1125 
   1126     def _get_slice_axis(self, slice_obj: slice, axis: int):

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis)
   1071     def _get_label(self, label, axis: int):
   1072         # GH#5667 this will fail if the label is not present in the axis.
-> 1073         return self.obj.xs(label, axis=axis)
   1074 
   1075     def _handle_lowerdim_multi_index_axis0(self, tup: Tuple):

~\anaconda3\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level)
   3737                 raise TypeError(f"Expected label or tuple of labels, got {key}") from e
   3738         else:
-> 3739             loc = index.get_loc(key)
   3740 
   3741             if isinstance(loc, np.ndarray):

~\anaconda3\lib\site-packages\pandas\core\indexes\range.py in get_loc(self, key, method, tolerance)
    352                 except ValueError as err:
    353                     raise KeyError(key) from err
--> 354             raise KeyError(key)
    355         return super().get_loc(key, method=method, tolerance=tolerance)
    356 

KeyError: 'row 1'

非常欢迎任何帮助!

【问题讨论】:

  • 您是否尝试使用 A 列作为索引,然后执行除法?也许可以成为解决您问题的好方法...
  • df['row4']=df.loc[row 1]/df.loc[row.2] 中的所有索引值都不适用于您的数据框。

标签: python pandas


【解决方案1】:

试试这个:

def append_value(index1, index2, shape):
    return {
        "Column A": f"row {shape}",
        "Values": df["Values"].iloc[index1]/df["Values"].iloc[index2]
    }


df.append(append_value(0, 1, df.shape[0]), ignore_index=True)

【讨论】:

  • 非常感谢,它几乎就在那里,但该列的标签名称显示为 NaN。有没有办法标记列?例如上面示例中的第 4 行。
猜你喜欢
  • 2020-08-04
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多