【问题标题】:Python, Pandas to calculate average with replicated rowsPython,Pandas 计算复制行的平均值
【发布时间】:2018-09-25 17:37:48
【问题描述】:

根据'n'列中的值复制行,并用平均值(v除以n)重新分配'v'列中的值,如下所示:

我正在关注Replicating rows in a pandas data frame by a column value 的示例。

import pandas as pd
import numpy as np

df = pd.DataFrame(data={
'id': ['A', 'B', 'C'],
'n' : [1, 2, 3],
'v' : [ 10, 13, 8]
})
df2 = df.loc[np.repeat(df.index.values,df.n)]

#pd.__version__ 0.20.3
#np.__version__ 1.15.0

但它返回了一条错误消息:

Traceback (most recent call last):
  File "C:\Python27\Working Scripts\pv.py", line 14, in <module>
df2 = df.loc[np.repeat(df.index.values, df.n)]
File "C:\Python27\lib\site-packages\numpy\core\fromnumeric.py", line 445, in repeat
return _wrapfunc(a, 'repeat', repeats, axis=axis)
File "C:\Python27\lib\site-packages\numpy\core\fromnumeric.py", line 61, in _wrapfunc
return _wrapit(obj, method, *args, **kwds)
File "C:\Python27\lib\site-packages\numpy\core\fromnumeric.py", line 41, in _wrapit
result = getattr(asarray(obj), method)(*args, **kwds)
TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'

这里出了什么问题,我该如何纠正?谢谢你。 (其他一些 pandas 和 numpy 脚本在计算机上都可以正常工作。)

【问题讨论】:

  • 我无法复制,它可以在我的机器上运行。我有 pandas 0.23.4,试试升级吧?
  • 它也适用于我。试试df.reindex(df.index.repeat(df.n))
  • @IMCoins,谢谢。我将 pandas 升级到 0.23.4,将 numpy 升级到 1.15.2,但还是一样。
  • @Abhi,升级了 Pandas 和 Numpy,还是一样...
  • 这些对我来说都是在黑暗中拍摄的,因为我无法复制。试试df.index.values.astype('int32') ?

标签: python pandas numpy dataframe


【解决方案1】:

我们通常每个主题只回答一个问题,但您可能不知道。 对于第一个问题,已在 cmets 中回答。投射到int32 明确解决了您的问题。

至于一般问题,您可以随时重新分配值...

import pandas as pd
import numpy as np

df = pd.DataFrame(data={
'id': ['A', 'B', 'C'],
'n' : [1, 2, 3],
'v' : [ 10, 13, 8]
})
df2 = df.loc[np.repeat(df.index.values,df.n)]
df2.loc[:, 'v'] = df2['v'] / df2['n']

print df2

#   id  n          v
# 0  A  1  10.000000
# 1  B  2   6.500000
# 1  B  2   6.500000
# 2  C  3   2.666667
# 2  C  3   2.666667
# 2  C  3   2.666667

我使用.loc 方法更正了df2['v'] = df2['v'] / df2['n'] 行,这是在pandas 中定位数据时的最佳做法。

如 cmets 中所述,它会引发警告。您可以看到 reading this link 这个警告确实误报。只要你知道你在做什么,你应该没问题。这个警告是为了告诉你 df.loc[] 方法返回了 DataFrame 的副本,而你没有使用它……因此你可能做错了。

tl;dr 从链接中,您可以禁用警告:

pd.options.mode.chained_assignment = None # default='warn'

【讨论】:

  • 再次感谢。很好的发现,完美解决了这个问题!
  • 它对 df2['v'] = df2['v'] / df2['n'] 也几乎没有警告。 “试图在 DataFrame 的切片副本上设置一个值。尝试改用 .loc[row_indexer,col_indexer] = value”。避免此警告的方法是什么?谢谢。
  • 太棒了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
  • 2014-02-04
  • 2021-11-08
  • 2019-04-19
  • 2020-01-08
  • 1970-01-01
相关资源
最近更新 更多