【问题标题】:Using .loc in division of columns calculation [duplicate]在列计算中使用 .loc [重复]
【发布时间】:2020-06-04 20:59:46
【问题描述】:

我希望以防止来自 python 的警告错误的方式进行以下计算:

我的表有以下一行的示例数据设置:

a b c d e f g

5 2 4 3 1 2 5

df['d'] = ((df['d']/df['c']))*100

如您所见,我希望用新计算的数字覆盖“xxx”列。我可以像上面那样做没有问题,但是 python 建议使用 loc 并且我无法获得正确的语法。

我正在寻找(3/4)*100 = 750

a b c  d  e f g

5 2 4 750 1 2 5

【问题讨论】:

    标签: python pandas division pandas-loc


    【解决方案1】:

    我使用 .iloc 来解决这个问题。

    我在这里重新创建了你的数据框 -

    import numpy as np
    import pandas as pd
    data = {'a':[5,2],'b':[2,3],'c':[4,4],'d':[3,5],'e':[1,2],'f':[2,3],'g':[5,6]}
    df = pd.DataFrame(data)
    df
    
       a    b   c   d   e   f   g
    0   5   2   4   3   1   2   5
    1   2   3   4   5   2   3   6
    

    这是分区 -

    df.loc['d'] = ((df.iloc[:,3]/df.iloc[:,2]))*100
    df
    
       a    b   c   d   e   f   g
    0   5   2   4   75.0    1   2   5
    1   2   3   4   125.0   2   3   6
    

    希望能解决你的问题

    【讨论】:

    • 谢谢。出于某种原因,我仍然收到以下错误:C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from DataFrame。尝试改用 .loc[row_indexer,col_indexer] = value
    • @AndrewK,这个修改对你有帮助吗 - df.loc['d'] = ((df.iloc[:,3]/df.iloc[:,2]))*100
    猜你喜欢
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 2017-01-13
    • 2014-07-04
    • 2018-08-01
    • 2018-11-23
    相关资源
    最近更新 更多