【问题标题】:Mapping Fields to Pull values within the same pandas dataframe映射字段以在同一熊猫数据框中提取值
【发布时间】:2022-10-04 16:25:00
【问题描述】:

我不确定用文字来描述这个的最佳方式是什么,所以一张图片值得一千字(在这种情况下,一个例子值得一千字:)) 我在 Python 上有这张表作为 Pandas 数据框

id Math Physics Morning Class Night Class
1 math100 phys300 [Math] [Physics]
2 math500 phys250A [Physics] [Math]

我正在尝试使用“Morning Class”和“Night Class”字段中的值来查看要查看的列并从中提取数据,并在此基础上替换“” Morning Class\" 和 \"Night Class\" 列值与来自 \"Math\" 和 \"Physics\" 字段的映射值。所以这就是决赛桌的样子

id Math Physics Morning Class Night Class
1 math100 phys300 math100 phys300
2 math500 phys250A phys250A math500

我想使用 Python 来实现这一点,我能够在 SQL 上做到这一点,我觉得这是一个简单的 Python 问题,但我似乎无法在 Python 中弄清楚,当我试图查找时在线我找不到任何描述和回答我的问题的帖子,如果已经存在,请随时向我推荐。感谢!!!

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    两列都使用indexing lookup

    cols1 = ['Morning Class','Night Class']
    
    def f(x):
        #if string columns
        idx, cols = pd.factorize(x.str.strip('[]'))
        #if one element list columns
        #idx, cols = pd.factorize(x.str[0])
        return df.reindex(cols, axis=1).to_numpy()[np.arange(len(df)), idx]
    
    df[cols1] = df[cols1].apply(f)
    print (df)
       id     Math   Physics Morning Class Night Class
    0   1  math100   phys300       math100     phys300
    1   2  math500  phys250A      phys250A     math500
    

    【讨论】:

      【解决方案2】:

      假设列中的值是字符串,那么我们可以尝试这样的事情:

      df.Morning_Class = df.apply(lambda x: x[x['Morning_Class'].strip('[]')],axis=1)
      df.Night_Class = df.apply(lambda x: x[x['Night_Class'].strip('[]')],axis=1)
      
      print(df)
      '''
        id     Math   Physics Morning_Class Night_Class
      0  1  math100   phys300       math100     phys300
      1  2  math500  phys250A      phys250A     math500
      

      【讨论】:

        猜你喜欢
        • 2022-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-10
        • 1970-01-01
        • 2015-09-30
        • 2021-05-25
        相关资源
        最近更新 更多