gpt4 book ai didi

python - 使用约束字典查询 Pandas

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:02 25 4
gpt4 key购买 nike

我正试图在某些年内抽出几个月的时间来处理 Pandas 。我有返回的约束 {month: year}。

 [{1: 2003},
{2: 2008},
{3: 2011},
{4: 2012},
{5: 2008},
{6: 2008},
{7: 2002},
{8: 2006},
{9: 2005},
{10: 2013},
{11: 2005},
{12: 2001}]

意味着我想要数据框中的 2003 年 1 月、2008 年 2 月等。我将“月”和“年”作为数据框中的两列。

我想要一些东西来执行这个不正确的代码(但想法很明确):

df[(df['Month'] == key for key in dict) & (df['Year'] == dict[key])]

最佳答案

您可以使用 lambda 在 Pandas 中执行高级过滤。

假设:

  1. 所有月份和年份都是整数
  2. 约束在字典列表类型中

如果数据类型不同,您可以修改以下行以解决您的问题。

生成随机数据填充数据框

In [1]: from random import randint 

In [2]: months = [randint(1, 12) for x in range(10)]

In [3]: years = [randint(2000, 2020) for x in range(10)]

In [4]: months
Out[4]: [12, 3, 7, 6, 10, 10, 11, 9, 9, 10]

In [5]: years
Out[5]: [2017, 2016, 2001, 2004, 2015, 2013, 2001, 2020, 2013, 2016]

In [6]: import pandas as pd

In [7]: df = pd.DataFrame()

In [8]: df['Month'] = months

In [9]: df['Year'] = years

<强>2。使用给定的 list of dict 并将其转换为 list of tuple 以便于编码

(注意:一旦您理解了我要完成的任务,您可以根据需要更改您的约束。)

In [10]: filterDict = [{1: 2003}, {2: 2008}, {3: 2011}, {4: 2012}, {5: 2008}, {6: 2008}, {7: 2002}, {8: 2006}, {9: 2005}, {3: 2016}, {6: 2004}, {12: 2001}]

In [11]: filterList = [d.items()[0] for d in filterDict]

<强>3。使用 lambda 过滤数据帧

In [12]: df[df.apply(lambda x: (x['Month'],x['Year']) in filterList, axis=1)]
Out[12]:
Month Year
1 3 2016
3 6 2004

过滤前的原始数据供您引用:

In [13]: df
Out[13]:
Month Year
0 12 2017
1 3 2016
2 7 2001
3 6 2004
4 10 2015
5 10 2013
6 11 2001
7 9 2020
8 9 2013
9 10 2016

关于python - 使用约束字典查询 Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33839980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com