【问题标题】:Python - unable to count occurences of values in defined ranges in dataframePython - 无法计算数据框中定义范围内值的出现次数
【发布时间】:2018-07-12 05:25:05
【问题描述】:

我正在尝试编写一个代码来分析数据框中的值,如果这些值属于一个类,那么这些值的总数将分配给字典中的一个键。但是代码对我不起作用。我正在尝试创建对数类并计算其中的值的总数

def bins(df):  
"""Returns new df with values assigned to bins"""  
bins_dict = {500: 0, 5000: 0, 50000: 0, 500000: 0}  
for i in df:  
    if 100<i and i<=1000:  
            bins_dict[500]+=1,  
    elif 1000<i and i<=10000:  
            bins_dict[5000]+=1  
print(bins_dict)  

但是,这是返回原始字典。

我也尝试过使用

修改数据框
def transform(df, range):   
for i in df:  
    for j in range:  
        b=10**j  
        while j==1:  
            while i>100:  
                if i>=b:  
                    j+=1,  
                elif i<b:  
                    b = b/2,  
                    print (i = b*(int(i/b)))  

此代码正在返回原始数据帧。

我的数据框仅包含一列,其值介于 100 和 10000000 之间

Data Sample:  
    Area  
0   1815  
1   907  
2   1815  
3   907  
4   907  

预期输出

dict={500:3, 5000:2, 50000:0}

如果我可以直接获得数据帧输出,那也会很有帮助 PS。我对编程很陌生,我只知道python

【问题讨论】:

  • 提供数据样本和您的预期输出。
  • 我已经更新了同样的帖子
  • 如果Area列的值小于500,它应该返回什么?
  • 所以目标是让所有介于 100 和 1000 之间的值都被计为针对 500 的发生,在 1000 和 10000 之间针对 5000 的值,等等

标签: python-3.x jupyter-notebook


【解决方案1】:

你需要使用 pandas:

import pandas as pd 

df = pd.DataFrame()
df['Area'] = [1815, 907, 1815, 907, 907]

# create new column to categorize your data
df['bins'] = pd.cut(df['Area'], [0,1000,10000,100000], labels=['500', '5000', '50000'])

# converting into dictionary 
dic = dict(df['bins'].value_counts())

print(dic)

输出:

{'500': 3, '5000': 2, '50000': 0}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-09
    • 2017-03-19
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    相关资源
    最近更新 更多