【问题标题】:Python Pandas dataframe division error: operation not ' 'safe' 'Python Pandas 数据框划分错误:操作不“安全”
【发布时间】:2017-02-20 12:21:18
【问题描述】:

我正在尝试将 Python 中 Pandas DataFrame 的某些列标准化为它们的总和。我有以下 DataFrame:

import pandas as pd
l_a_2015 = ['Farh','Rob_Sens','Pressure','Septic',10.0,45.,52.,72.51]
l_a_2010 = ['Water_Column','Log','Humid','Top_Tank',58.64,35.42,10.,30.]

df = pd.DataFrame([l_a_2010,l_a_2015],columns=['Output_A','Tonnes_Rem',
                                               'Log_Act_All','Readout','A1','A2','A3','A4'])

我想将 A1,A2,A3,A4 列标准化为它们的总和,如图所示 here - 将一行中的每个元素除以 4 个元素的总和。

第一部分似乎工作正常 - 我得到了每一行最后 4 列的总和:

x,y = df.sum(axis=1).tolist()

所以,[x,y] 列表给了我第一行和第二行(最后 4 列)的总和。但是,当我尝试将每行上的所有 DataFrame 条目除以该行的总和时,我遇到了问题:

for b,n in enumerate([x,y]):
    for f,elem in enumerate(list(df)[4:]):
        df.iloc[b,f] = (df.iloc[b,f]/n)*100.

我收到以下错误:

[Traceback (most recent call last):134.06, 179.50999999999999]

  File "C:\test.py", line 13, in <module>
    df.iloc[b,f] = (df.iloc[b,f]/n)*100.
TypeError: ufunc 'divide' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

当我使用print df.dtypes 时,所有列都得到float64,所以我不确定为什么划分不安全。

有吗

【问题讨论】:

    标签: python pandas dataframe divide


    【解决方案1】:

    试试这个:

    In [5]: df
    Out[5]:
           Output_A Tonnes_Rem Log_Act_All   Readout     A1     A2    A3     A4
    0  Water_Column        Log       Humid  Top_Tank  58.64  35.42  10.0  30.00
    1          Farh   Rob_Sens    Pressure    Septic  10.00  45.00  52.0  72.51
    
    In [8]: cols = df.select_dtypes(include=['number']).columns.tolist()
    
    In [9]: cols
    Out[9]: ['A1', 'A2', 'A3', 'A4']
    

    让我们创建一个仅包含数字列的视图:

    In [10]: v = df[cols]
    
    In [13]: df[cols] = v.div(v.sum(axis=1), 0)
    
    In [14]: df
    Out[14]:
           Output_A Tonnes_Rem Log_Act_All   Readout        A1        A2        A3        A4
    0  Water_Column        Log       Humid  Top_Tank  0.437416  0.264210  0.074593  0.223780
    1          Farh   Rob_Sens    Pressure    Septic  0.055707  0.250682  0.289677  0.403933
    

    另一种选择A* 列的方法:

    In [18]: df.filter(regex='^A\d+')
    Out[18]:
             A1        A2        A3        A4
    0  0.437416  0.264210  0.074593  0.223780
    1  0.055707  0.250682  0.289677  0.403933
    
    In [19]: df.filter(regex='^A\d+').columns
    Out[19]: Index(['A1', 'A2', 'A3', 'A4'], dtype='object')
    

    【讨论】:

    • 谢谢!实际上,我刚刚意识到我链接到的帖子 (here) 包含相同的方法。我认为这不适用于我的数据框中的非数字列。您的方法在解释上更加直观。再次感谢!
    猜你喜欢
    • 2014-11-03
    • 2016-11-04
    • 2014-03-05
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2018-09-11
    • 2013-05-17
    • 1970-01-01
    相关资源
    最近更新 更多