【问题标题】:How to write a nested query with in python pandas?如何在 python pandas 中编写嵌套查询?
【发布时间】:2018-03-13 21:51:39
【问题描述】:

大家好,我是熊猫新手。我需要一些关于如何为我需要的输出编写 pandas 查询的帮助。

我想检索输出数据,例如 当 0

我的输入数据看起来像:

population,minimum_age,maximum_age,gender,zipcode,geo_id 
50,30,34,f,61747,8600000US61747 
5,85,NaN,m,64120,8600000US64120 
1389,10,34,m,95117,8600000US95117  
231,5,60,f,74074,8600000US74074
306,22,24,f,58042,8600000US58042

我的代码:

import pandas as pd
import numpy as np
df1 = pd.read_csv("C:\Users\Rahul\Desktop\Desktop_Folders\Code\Population\population_by_zip_2010.csv")
df2=df1.set_index("geo_id")
df2['sum_population'] = np.where(df2['minimum_age'] < 10,sum(df2['population']),0)
print df2

【问题讨论】:

  • 你试过了吗?
  • 是的,我已经尝试过了,但它没有得到我检索到的输出
  • 无论你尝试什么都发布你的代码
  • 更重要的是,对于这个数据,一些预期的输出会很好。
  • @Roshan 我已经发布了

标签: python python-2.7 python-3.x pandas


【解决方案1】:

你可以试试 pandas cut 和 groupby,

df.groupby(pd.cut(df['minimum_age'], bins=np.arange(0,100, 10), right=False)).population.sum().reset_index(name = 'sum of population')

    minimum_age sum of population
0   [0, 10)     231.0
1   [10, 20)    1389.0
2   [20, 30)    306.0
3   [30, 40)    50.0
4   [40, 50)    NaN
5   [50, 60)    NaN
6   [60, 70)    NaN
7   [70, 80)    NaN
8   [80, 90)    5.0

说明:Pandas cut 通过将它们按 0-10、10-20 等分组来帮助创建 minimum_age 的 bin。看起来是这样的

pd.cut(df['minimum_age'], bins=bins, right=False)

0    [30, 40)
1    [80, 90)
2    [10, 20)
3     [0, 10)
4    [20, 30)

现在我们在 pd.cut 的输出上使用 groupby 来查找总体总和。

【讨论】:

  • 非常感谢您的快速解答和时间。太感谢了。你能解释一下你的查询行组将做什么,其中有 pd.cut,bins
  • 我已经添加了一些解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-02
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-01
  • 1970-01-01
相关资源
最近更新 更多