【问题标题】:How to convert each values in Data Frame to int and float in only one index row in Python Pandas?如何将 Data Frame 中的每个值转换为 int 并仅在 Python Pandas 的一个索引行中浮动?
【发布时间】:2021-11-09 12:16:48
【问题描述】:

我在 Python 中有 Pandas 数据框,如下所示:

IDX  | ALL | COL1 | COL2
------------------------
ABC  | 100 | 50   | 214
DEF  | 250 | 32   | 89
GHI  | 120 | 18   | 12

IDX 是这个数据帧的索引。 我想在这个数据框中添加新行,它将计算数学公式,如:

(value from index DEF - value from index GHI) and result / by value from index DEF

例如:(250 - 120) / 250 = 0.52 所以我需要类似下面的东西:

IDX  | ALL | COL1 | COL2
------------------------
ABC  | 100 | 50   | 214
DEF  | 250 | 32   | 89
GHI  | 120 | 18   | 12
new1 | 0.52| 0.44 | 0.87

因为:

(250 - 120) / 250 = 0.52
(32 - 18) / 32 = 0.44
(89 - 12) / 89 = 0.87

我使用如下代码:

df.loc['new1'] = df.lfoc['DEF'].sub(df.floc['GHI']).div(df.loc['DEF'])

尽管如此,在使用上述代码(有效)后,我的 DF 中的值从 int 更改为 float,如下所示:

IDX  | ALL | COL1 | COL2
------------------------
ABC  | 100.00000 | 50.00000   | 214.00000
DEF  | 250.00000 | 32.00000   | 89.00000
GHI  | 120.00000 | 18.00000   | 12.00000
new1 | 0.52000   | 0.43750    | 0.86516

我能做些什么来实现如下的 DF???:

IDX  | ALL | COL1 | COL2
------------------------
ABC  | 100 | 50   | 214
DEF  | 250 | 32   | 89
GHI  | 120 | 18   | 12
new1 | 52.0| 43.7 | 86.5

【问题讨论】:

    标签: python pandas dataframe indexing


    【解决方案1】:

    pandas默认每一列的类型都是相同的,所以close是多除,但还是有float列:

    df.loc['new1'] = df.loc['DEF'].sub(df.loc['GHI']).div(df.loc['DEF']).mul(100).round(1)
    print (df)
            ALL  COL1   COL2
    IDX                     
    ABC   100.0  50.0  214.0
    DEF   250.0  32.0   89.0
    GHI   120.0  18.0   12.0
    new1   52.0  43.8   86.5
    

    可能的解决方案是转置 - 原始整数不变,新列由浮点数填充:

    df = df.T
    df['new1'] = df['DEF'].sub(df['GHI']).div(df['DEF']).mul(100).round(1)
    print (df)
    IDX   ABC  DEF  GHI  new1
    ALL   100  250  120  52.0
    COL1   50   32   18  43.8
    COL2  214   89   12  86.5
    

    格式化者的另一个想法g

    df = df.applymap('{:,g}'.format)
    print (df)
          ALL  COL1  COL2
    IDX                  
    ABC   100    50   214
    DEF   250    32    89
    GHI   120    18    12
    new1   52  43.8  86.5
    

    或者转成字符串:

    df.loc['new1'] = df.loc['DEF'].sub(df.loc['GHI']).div(df.loc['DEF']).mul(100).round(1).astype(str)
    df = df.astype(str)
    
    print (df)
           ALL  COL1  COL2
    IDX                   
    ABC    100    50   214
    DEF    250    32    89
    GHI    120    18    12
    new1  52.0  43.8  86.5
    

    【讨论】:

    • 不幸的是,您答案中第二个单元格的代码不起作用,您是否考虑到 IDX 是数据透视表的索引?
    • @Matop - 如果需要数字列,在一列中混合整数和浮点数是有问题的。 pandas 总是转换成浮点数 :(
    • 所以也许我们可以将所有值更改为 str 然后从 str 中删除 dot 之后的所有内容?你怎么看 ?你能试试吗?
    • 转换为字符串,然后在没有索引“new1”的每个索引中删除点后的所有值我认为它可以工作
    • 太好了,谢谢! str 的解决方案工作
    猜你喜欢
    • 2021-11-09
    • 2017-02-14
    • 1970-01-01
    • 2022-11-14
    • 2016-04-26
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多