【问题标题】:Calculating and creating percentage column from two columns从两列计算和创建百分比列
【发布时间】:2016-07-19 19:59:18
【问题描述】:

我有一个 df (Apple_farm),需要根据其中两列(Good_applesTotal_apples)中的值计算百分比,然后将结果值添加到 Apple_farm 中名为 ' 的新列Perc_Good'。

我试过了:

Apple_farm['Perc_Good'] = (Apple_farm['Good_apples'] / Apple_farm['Total_apples']) *100

然而这会导致这个错误:

TypeError: /: 'str' 和 'str' 的操作数类型不受支持

在做

Print Apple_farm['Good_apples']Print Apple_farm['Total_apples']

产生一个包含数值的列表,但是将它们分开似乎会导致它们被转换为字符串?

我也尝试定义一个新函数:

def percentage(amount, total):
    percent = amount/total*100
    return percent

但不确定如何使用它。

任何帮助都将不胜感激,因为我对 Python 和 pandas 还很陌生!

【问题讨论】:

    标签: python string pandas dataframe percentage


    【解决方案1】:

    我认为您需要将string 列转换为floatint,因为它们的typestring(但看起来像数字):

    Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(float)
    Apple_farm['Total_apples'] = Apple_farm['Total_apples'].astype(float)
    
    Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(int)
    Apple_farm['Total_apples'] = Apple_farm['Total_apples'].astype(int)
    

    示例:

    import pandas as pd
    
    Good_apples = ["10", "20", "3", "7", "9"]
    Total_apples = ["20", "80", "30", "70", "90"]
    d = {"Good_apples": Good_apples, "Total_apples": Total_apples}
    Apple_farm = pd.DataFrame(d)
    print Apple_farm 
      Good_apples Total_apples
    0          10           20
    1          20           80
    2           3           30
    3           7           70
    4           9           90
    
    print Apple_farm.dtypes
    Good_apples     object
    Total_apples    object
    dtype: object
    
    print Apple_farm.at[0,'Good_apples']
    10
    
    print type(Apple_farm.at[0,'Good_apples'])
    <type 'str'>
    
    Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(int)
    Apple_farm['Total_apples'] = Apple_farm['Total_apples'].astype(int)
    
    print Apple_farm.dtypes
    Good_apples     int32
    Total_apples    int32
    dtype: object
    
    print Apple_farm.at[0,'Good_apples']
    10
    
    print type(Apple_farm.at[0,'Good_apples'])
    <type 'numpy.int32'>
    
    Apple_farm['Perc_Good'] = (Apple_farm['Good_apples'] / Apple_farm['Total_apples']) *100
    
    print Apple_farm
       Good_apples  Total_apples  Perc_Good
    0           10            20       50.0
    1           20            80       25.0
    2            3            30       10.0
    3            7            70       10.0
    4            9            90       10.0
    

    【讨论】:

    • 那个苹果农场需要找到一些更好的苹果
    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 2015-01-02
    • 2022-01-14
    • 1970-01-01
    • 2022-12-05
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多