大熊猫数据帧的高效管理

时间:2013-09-11 14:39:12

标签: python python-2.7 pandas panel dataframe

我的第一个StackOverflow问题。

所以我有一个看起来像这样的Pandas DataFrame:

String1 String2 String3 value
word1 word2 word3 5.6
word4 word5 word6 123.4
...

这种DataFrame来自基于大量文本的非常长的处理链。 (作为旁注,我接近内存限制,现在正在考虑HDF商店。)

现在,我想基于将此表转换为(稀疏?)面板或其他类型的有效数据结构来完成线性代数运算,这些数据结构填充空白为0。也就是说,我想创建一个表,其行是String3s,其列是String1 x String2对,然后对行进行线性代数运算。但是,我还希望能够对任何其他列执行相同的操作 - 即,将String1作为行,并使用String2 x String3创建列。

我一直在试验Panels和数据透视表,但它们似乎不太正确,而且它们经常溢出内存。

一般来说,使用Pandas或Python(2.7)这样做的正确方法是什么?

编辑添加此示例:

输出表将如下所示:

String1String2 (word1,word2) (word1,word5) (word4,word2) (word4,word5) ...
String3
word3 5.6 0 0 0 ...
word6 0 0 0 123.4 ...

列数基本上是| String1 | x | String2 |。 或者,String3作为列,String1String2作为行也可以,因为我可以对列系列执行操作。

进一步编辑以添加内存问题:

In [1]: import pandas as pd

In [2]: A = pd.load("file.df")

In [3]: A 
Out[3]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 18506532 entries, 0 to 18506531
Columns: 4 entries, 0 to value
dtypes: float64(1), object(3)

In [4]: B = A[A[1] == 'xyz']

In [5]: C = B.pivot_table('value', [1,2], 0)

它在reshape.pyc的第160行与MemoryError崩溃。这是pandas的0.11.0版本。

1 个答案:

答案 0 :(得分:1)

您可以使用pivot_table执行此操作:

In [11]: res = df.pivot_table('value', 'String3', ['String1', 'String2'])

In [12]: res
Out[12]: 
String1  word1  word4
String2  word2  word5
String3              
word3      5.6    NaN
word6      NaN  123.4

此结果可能已足够,但如果您需要空白列,则可以使用itertools.product。

In [13]: from itertools import product

In [14]: res = res.reindex(columns=list(product(df['String1'], df['String2'])))

In [15]: res.columns.names = ['String1', 'String2']

In [16]: res
Out[16]: 
String1  word1         word4       
String2  word2  word5  word2  word5
String3                            
word3      5.6    NaN    NaN    NaN
word6      NaN    NaN    NaN  123.4

并填写0:

的空白
In [17]: res.fillna(0)
Out[17]: 
String1  word1         word4       
String2  word2  word5  word2  word5
String3                            
word3      5.6      0      0    0.0
word6      0.0      0      0  123.4

注意:在cartesian_product中可以使用0.13 pandas.tools.util