2016-05-12 67 views
2

我目前面临正在采取大熊猫数据帧,有效地采取每个记录并将其分解成多个记录以下列方式问题:大熊猫:拆分一行到多行高效

输入:

In [16]: pd.DataFrame({'Name': 'Person1', 'State': 'Indiana', 'Money1': 100.42, 'Money2':54.54, 'Money3': 23.45}, index=[1]) 
Out[16]: 
    Money1 Money2 Money3 Name  State 
1 100.42 54.54 23.45 Person1 Indiana 

输出:

Money1 Money2 Money3 Name  State 
1 100.42 np.nan np.nan Person1 Indiana 
2 np.nan 54.54 np.nan Person1 Indiana  
3 np.nan np.nan 23.45 Person1 Indiana 

本质上来说,问题是分裂原纪录为X个记录,其中x是在柱后通过(i拆分列表在这种情况下,'Money1','Money2','Money3'。我曾尝试通过创建DataFrames并将它们连接起来,但这非常缓慢且内存效率低下。

EDIT1:

请不,答案不一样,如果你的静态列(即都变成了多指标的那些)甚至一个充满不同的NaN工作。这是大熊猫报告的错误: https://github.com/pydata/pandas/issues/6322

要解决它,使用fillnareplace填写完全的NaN与空字符串''包括列,例如,然后在这个过程之后,把NaN回。

回答

1

这应该适用于具有任意数量列的数据帧。

df = pd.DataFrame({'Name': ['Person1', 'Person2'], 
        'State': ['Indiana', 'NY'], 
        'Money1': [100.42, 200], 
        'Money2': [54.54, 25], 
        'Money3': [23.45, 10]}) 

index_cols = ['Name', 'State'] 
cols = [c for c in df if c not in index_cols] 

df2 = df.set_index(index_cols).stack().reset_index(level=2, drop=True).to_frame('Value') 

df2 = pd.concat([pd.Series([v if i % len(cols) == n else np.nan 
          for i, v in enumerate(df2.Value)], name=col) 
       for n, col in enumerate(cols)], axis=1).set_index(df2.index) 

>>> df2.reset_index() 
     Name State Money1 Money2 Money3 
0 Person1 Indiana  1  NaN  NaN 
1 Person1 Indiana  NaN  55  NaN 
2 Person1 Indiana  NaN  NaN  23 
3 Person2  NY  2  NaN  NaN 
4 Person2  NY  NaN  25  NaN 
5 Person2  NY  NaN  NaN  10 
+0

调用'df2.reset_index(drop = False)'在上述过程之后将其转换为我想要的格式。 – Zeke