【问题标题】:Dividing all elements in a single row of a DataFrame by an element in another column in that same row and then do this for all rows using pandas?将DataFrame单行中的所有元素除以同一行中另一列中的元素,然后使用pandas对所有行执行此操作?
【发布时间】:2021-05-21 14:04:57
【问题描述】:

假设我有一个如下所示的简单数据框,我想将 column_4 中的第 i 个元素划分为该特定行的所有其他列(column_4 除外)中的第 i 个元素,然后执行此操作在所有行上。

另一种说法是如何按第 4 列标准化第 1、2、3 列?有没有简单的方法可以做到这一点?

例如

输入

import pandas as pd

df = pd.DataFrame({'column_1':[1,2,3], 'column_2':[4,5,6], 'column_3':[7,8,9], 'column_4':[2,3,4]})
df.head()

期望的输出

df2 = pd.Dataframe({'column_1':[1/2,2/3,3/4], 'column_2':[4/2,5/3,6/4], 'column_3':[7/2,8/3,9/4], 'column_4':[2,3,4]})
df2.head()

注意column_1,column_2,column_3 中的每个元素都已除以column_4 中的等效元素。

注意:在这种情况下,我使用了一个相对较小的 DataFrame,但我也想知道是否有一种方法可以概括具有 1000 行和 100 列的 DataFrame 的结果。

【问题讨论】:

    标签: python pandas dataframe normalization


    【解决方案1】:

    选项 1

    你可以这样做

    df['column_1'] = df['column_1'] / df['column_4']
    

    等等

    操作被向量化,就像在 numpy 中一样

    如果你想要一个新的数据框做

    In [18]: import pandas as pd
        ...: df = pd.DataFrame({'column_1':[1,2,3], 'column_2':[4,5,6], 'column_3':[7,8,9], 'column_4
        ...: ':[2,3,4]})
        ...: df.head()
    Out[18]:
       column_1  column_2  column_3  column_4
    0         1         4         7         2
    1         2         5         8         3
    2         3         6         9         4
    
    In [19]: new_df = pd.DataFrame()
    
    In [20]: for col in ['column_1', 'column_2', 'column_3']:
        ...:     new_df[col] = df[col] / df['column_4']
        ...:
    
    In [21]: new_df
    Out[21]:
       column_1  column_2  column_3
    0  0.500000  2.000000  3.500000
    1  0.666667  1.666667  2.666667
    2  0.750000  1.500000  2.250000
    
    

    选项 2

    正如 anky 所指出的,您可以像这样在一个班轮中解决这个问题:

    df.drop('column_4',1).div(df['column_4'],axis=0)
    

    【讨论】:

      猜你喜欢
      • 2016-08-03
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 2012-07-18
      • 2018-10-06
      • 2019-05-17
      • 2020-10-02
      • 2021-07-21
      相关资源
      最近更新 更多