【问题标题】:Open AI - python data wrangling - filter pandas dataframe values by a seperate dictionary with tuples as the keysOpen AI - python data wrangling - 通过单独的字典过滤 pandas dataframe 值,以元组为键
【发布时间】:2022-12-15 15:32:32
【问题描述】:

我有一个数据整理任务,我想以某种格式保存输入。当我感到疲倦时,我决定尝试使用 OpenAI,看看代码生成能做什么。它得出了与我最初追求的不同的解决方案。如果这是一件好事,我仍然有点犹豫,特别是对于那些刚刚学习编码的人,但这是一个不同的主题。

迅速的:

create a python function to filter pandas dataframe values by a seperate dictionary with tuples as the keys 

for example:
I have a dataframe named "temp_obs"  like pd.DataFrame([[2000, January, 1,2,3],[2000, March,3,3],[2004, December,2,6,1,2] ,[1993, December,2]]
I have a dictionary named "phase" with keys as tuples corresponding to the dataframe columns and rows, like this {(2000,January):0, (2000,March):3, (2004,December):3, (1993,December):0, (1999,March):5 ,(2020,January):1}.

I want to filter the dataframe such that I only get the rows with the corresponding dictionary values greater than 2.

the output would be a dataframe with rows  [2000, March,3,3] and [2004, December,2,6,1,2]

【问题讨论】:

    标签: python pandas openai


    【解决方案1】:

    通过 OpenAI 回答。

    A:

    You can use <code>pd.DataFrame.isin</code> to filter the dataframe.
    <code>temp_obs = pd.DataFrame([[2000, 'January', 1,2,3],[2000, 'March',3,3],[2004, 'December',2,6,1,2] ,[1993, 'December',2]])
    
    phase = {(2000,'January'):0, (2000,'March'):3, (2004,'December'):3, (1993,'December'):0, (1999,'March'):5 ,(2020,'January'):1}
    
    temp_obs[temp_obs.isin(phase.keys()).sum(1) &gt; 2]
    </code>
    Output:
    <code>  
        0      1       2  3  4  5
    
    1  2000    March   3  3  0  0
    2  2004  December  2  6  1  2
    </code>
    

    【讨论】:

      猜你喜欢
      • 2015-12-22
      • 2013-07-01
      • 1970-01-01
      • 2023-02-24
      • 2020-08-06
      • 2011-07-26
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      相关资源
      最近更新 更多