【问题标题】:Making multiple tables based off another table?根据另一个表制作多个表?
【发布时间】:2023-03-23 02:22:01
【问题描述】:

我有许多列的格式为“NameX(TypeY)”。格式是这样的:

total =  pd.DataFrame(table):

         NameA(Type1)    NameA(Type2)    NameA(Type3)   NameB(Type1)   NameB(Type2)    NameB.(Type3)
set1           1               1              1             2              3               4
set2           2               3              1             1              0               2
set3           2               2              1             0              0               3

所以我现在的目标是以这种格式为每个名称(A,B,X...)获取一个表格,我不想更改设置的行,因此名称 A 的示例输出将是:

     Type1       Type2       Type3
set1    1           1           1
set2    2           3           1 
set3    2           2           1

我正在考虑以某种方式使用 for 循环,但不太清楚如何获得多个这样的表。

任何帮助将不胜感激!我对编程和 python 还很陌生,所以仍在研究一些更基本的原则

【问题讨论】:

    标签: python python-3.x pandas filter


    【解决方案1】:

    试试这个:

    对于一个:

    df2 = df.filter(like='NameA', axis=1).rename(columns=lambda x: x.replace('NameA', '').replace('(', '').replace(')', ''))
    

    对于列表:

    Dflist = ['NameA','NameB' ] 
    DfDict = {}
    
    for e in Dflist: 
        out = df.filter(like=e, axis=1).rename(columns=lambda x: x.replace(e, '').replace('(', '').replace(')', ''))
    #     print out , "\n"
        DfDict[e] = out
    
    DfDict["NameA"]
    
    #      Type1  Type2  Type3
    # set1      1      1      1
    # set2      2      3      1
    # set3      2      2      1
    

    【讨论】:

      【解决方案2】:
      from collections import defaultdict
      
      dfs = defaultdict(pd.DataFrame)
      
      for name_sample, series in df.iteritems():
          name, sample = name_sample.split('.')
          dfs[name][sample] = series
      

      上面为您提供了一个字典,每个唯一的“名称”都有一个表:

              {'NameA':      Sample#1  Sample#2  Sample#3
               id                               
               id1         1         1         1
               id2         2         3         1
               id3         2         2         1,
               'NameB':      Sample#1  Sample#2  Sample#3
               id                               
               id1         2         3         4
               id2         1         0         2
               id3         0         0         3}
      

      这依赖于您可以在构造后将列添加到 DataFrame 的事实,并且它使用 defaultdict 来获得外部容器的类似行为。

      无论行数如何,性能都应该不错,但是如果您有大量列,可能会有更好的方法(因为上面依赖于列上的 Python 循环)

      【讨论】:

      • 感谢您的回复!我仍然对这种方法有一点麻烦!每当我尝试使用 name_sample.split('.') 行时,我都会收到一个值错误,提示“没有足够的值来解包”。有什么想法吗?
      • @CallieJester:那是因为我写了对您最初问题的回答。从那时起,您将列命名约定从 NameA.Sample#1 更改为 NameA(Type1)。我相信您可以从我关于字符串处理的答案中的链接中找出如何从新的列名格式中获取名称。我不会更新我的答案,因为在你已经回答过一次之后更改问题的数据格式是不公平的。
      猜你喜欢
      • 1970-01-01
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      相关资源
      最近更新 更多