【问题标题】:pandas: apply a function to the many columns of a large DataFrame to return multiple rowspandas:将函数应用于大型 DataFrame 的许多列以返回多行
【发布时间】:2014-07-13 05:52:30
【问题描述】:

从这个答案中汲取灵感:pandas: apply function to DataFrame that can return multiple rows

就我而言,我有类似的东西,但更大:

    df = pd.DataFrame({'Restaurants': ['A', 'B', 'C'], 
                       'Tables':['D', 'E', 'F'], 
                       'Chairs': ['G', 'H', 'I'], 
                       'Menus': ['J', 'K', 'L'], 
                       'Fridges': ['M', 'N', 'O'], 
                       'Etc...': ['P', 'Q', 'R'], 'count':[3, 2, 3]})

   Restaurants  Tables Chairs Menus Fridges  Etc... Count
 0           A       D      G     J       M       P     3
 1           B       E      H     K       N       Q     2
 2           C       F      I     L       O       R     3

我想修改这个:

def f(group):
    row = group.irow(0)
    return DataFrame({'class': [row['class']] * row['count']})
df.groupby('class', group_keys=False).apply(f)

所以我可以得到

    Restaurants  Tables Chairs Menus Fridges  Etc...
 0           A       D      G     J       M        P
 1           A       D      G     J       M        P           
 2           A       D      G     J       M        P           
 0           B       E      H     K       N        Q           
 1           B       E      H     K       N        Q
 0           C       F      I     L       O        R
 1           C       F      I     L       O        R
 2           C       F      I     L       O        R

有没有不输入每一列名称的简单方法?

【问题讨论】:

  • 为什么要这样做?如,您确定这实际上是您想要做的吗?

标签: python pandas data-analysis


【解决方案1】:
#!/usr/bin/env python

import pandas as pd
from collections import defaultdict

d = defaultdict(list)
for n in range(len(df)):
    for c in df.columns.tolist()[:-1]:
        k = [df.ix[n][c]] * df.ix[n]['count']
        for ks in k:
            d[c].append(ks)
    for j in range(df.ix[n]['count']):
        d['index'].append(j)

new_df = pd.DataFrame(d, index=d['index']).drop(['index'], axis = 1)
new_df

        Restaurants  Tables Chairs Menus Fridges  Etc...
 0           A       D      G     J       M        P
 1           A       D      G     J       M        P           
 2           A       D      G     J       M        P           
 0           B       E      H     K       N        Q           
 1           B       E      H     K       N        Q
 0           C       F      I     L       O        R
 1           C       F      I     L       O        R
 2           C       F      I     L       O        R

【讨论】:

  • 非常感谢!这正是我所需要的!
猜你喜欢
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 2018-06-07
  • 2018-01-01
  • 2019-11-26
  • 2021-03-16
相关资源
最近更新 更多