简体   繁体   English

pandas pivot table,通过获取多列的差异来创建表

[英]pandas pivot table, creating table by taking difference of multiple columns

I have this pivot table that has a 2 level column filter. 我有这个具有2级列过滤器的数据透视表。

table_pivot = pandas.pivot_table(table_raw, values='PRICE', index=['DATE', 'HOUR'],
                             columns=['TYPE', 'ID'], aggfunc= numpy.mean, fill_value= 0)

output pivot looks like this: output pivot看起来像这样:

TYPE                 type X         type Y
ID                  X1  X2  X3     Y1  Y2  Y3  Y4
DATE      HOUR 
1/1/2015  1       10  20  30     20  40  60  80
1/1/2015  2       20  40  60     10  50  70  90 

Now I'm trying to get the difference between the types such that intended output looks something like this: 现在我试图获得类型之间的差异,使得预期输出看起来像这样:

                  Z
                  Y1 - X1    Y1 - X2    Y1 - X3    Y1 - X1   Y2 - X1 ....
Date      Hour 
1/1/2015  1         10         20         30          40        30   ... 
1/1/2015  2        -10         30         50          70       -30   ...

I thought it would be something like: 我以为它会是这样的:

table_pivot['Z'] = table_pivot['Y'] - table['X']

But it appears It does not work. 但似乎它不起作用。 How do I create a new table to get the difference between all possible XY combinations? 如何创建新表以获得所有可能的XY组合之间的差异?

UPDATE: I tried the following lines. 更新:我尝试了以下几行。 However, I've been getting the MemoryError message. 但是,我一直在收到MemoryError消息。 Does anyone know how I can remedy this? 有谁知道如何解决这个问题?

x_list = table_pivot['X'].columns.values
y_list = table_pivot['Y'].columns.values

table_diff = pandas.DataFrame()

for each_x in x_list:
    for each_y in y_list:
        colName = each_y + ' - ' + each_x
        table_diff[colName] = table_pivot['Y'][each_y] - table_pivot['X'][each_x]

A case of multi index slicing, sub() and concat. 一个多索引切片,sub()和concat的情况。

df = pd.DataFrame({('Y', 'Y4'): {('1/1/2015', 2L): 90, ('1/1/2015', 1L): 80}, ('X', 'X1'): {('1/1/2015', 2L): 20, ('1/1/2015', 1L): 10}, ('X', 'X2'): {('1/1/2015', 2L): 40, ('1/1/2015', 1L): 20}, ('X', 'X3'): {('1/1/2015', 2L): 60, ('1/1/2015', 1L): 30}, ('Y', 'Y3'): {('1/1/2015', 2L): 70, ('1/1/2015', 1L): 60}, ('Y', 'Y1'): {('1/1/2015', 2L): 10, ('1/1/2015', 1L): 20}, ('Y', 'Y2'): {('1/1/2015', 2L): 50, ('1/1/2015', 1L): 40}})
df.columns = pd.MultiIndex.from_tuples([('X','X1'), ('X','X2'), ('X','X3'),('Y','Y1'), ('Y','Y2'), ('Y','Y3'), ('Y', 'Y4')])
df.index.names = ['DATE','ID']
print df


              X           Y            
             X1  X2  X3  Y1  Y2  Y3  Y4
DATE     ID                            
1/1/2015 1   10  20  30  20  40  60  80
         2   20  40  60  10  50  70  90


idx = pd.IndexSlice
collection = []
for tup in filter(lambda x: x[0] == "Y", df.columns.tolist()):
    foo = -1 * df.loc[:,idx['X',:]].sub(df.loc[:,tup],axis=0)
    foo.columns = [str(tup[1]) + '-' + col for col in foo.columns.get_level_values(1)]
    collection.append(foo)

print pd.concat(collection,axis=1)


             Y1-X1  Y1-X2  Y1-X3  Y2-X1  Y2-X2  Y2-X3  Y3-X1  Y3-X2  Y3-X3  Y4-X1  Y4-X2  Y4-X3
DATE     ID                                                                                    
1/1/2015 1      10      0    -10     30     20     10     50     40     30     70     60     50
         2     -10    -30    -50     30     10    -10     50     30     10     70     50     30

Possible better way to do this is by using a time series data frame for each variable, then creating another data frame with the difference between the variables. 可能更好的方法是为每个变量使用时间序列数据帧,然后创建另一个数据框,其中包含变量之间的差异。

data = pd.read_csv('file_path', index_column)

#assuming data is in date-time format
data.index() = pd.to_datetime(data.index())

xvars = data.type['X']
yvars = data.type['Y']

Then use the same for loop logic for taking Yi - Xi and storing that in a new data frame. 然后使用相同的for循环逻辑来获取Yi-Xi并将其存储在新的数据帧中。

May not throw the memory error by keeping objects simple. 保持对象简单可能不会引发内存错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM