2017-06-22 51 views
1

將表或矩陣從python分解爲包含來自列及其值的信息的行的最佳解決方案(性能)是什麼?將表分解爲熊貓中的行

讓我們說我們有大熊貓裝載表如下所示:

Date A B 
t1 1 2 
t2 3 4 

我要爆表,這樣就變成了一系列的4條線路如下:

t1-A-1 
t1-B-2 
t2-A-3 
t2-C-4 

性能在原始表中可能有數十列和數百行的情況下,關鍵在於此。

何談以下幾點:

Date A B C 
t1 1 5 9 
t1 2 6 10 
t2 3 7 11 
t2 4 8 12 

輸出系列將是:

Date code 
t1 "str1"1"str2"B"str2"5 
t1 "str1"2"str2"B"str2"6 
t2 "str1"3"str2"B"str2"7 
t2 "str1"4"str2"B"str2"8 
.. .. 
t2 "str1"4"str2"C"str2"12 

我感謝您的幫助!

+2

恰好B5和C3是什麼? – Allen

回答

2
df.set_index('Date').stack().reset_index().apply(lambda x: '-'.join(x.astype(str)), axis=1) 

輸出:

0 t1-A-1 
1 t1-B-2 
2 t2-A-3 
3 t2-B-4 
dtype: object 
+0

太棒了!謝謝。 – Guga

3

如果性能是關鍵......用numpy

from numpy.core.defchararray import add as cadd 
from functools import reduce 

def proc(d1): 
    v = d1.values 
    n, m = v.shape 
    dates = np.repeat(d1.index.values.astype(str), m) 
    cols = np.tile(d1.columns.values.astype(str), n) 
    vals = v.ravel().astype(str) 
    return pd.Series(reduce(cadd, [dates, '-', cols, '-', vals])) 

proc(df.set_index('Date')) 

0 t1-A-1 
1 t1-B-2 
2 t2-A-3 
3 t2-B-4 
dtype: object 

定時

%timeit proc(df.set_index('Date')) 
%timeit df.set_index('Date').stack().reset_index().apply(lambda x: '-'.join(x.astype(str)), axis=1) 

小數據

1000 loops, best of 3: 494 µs per loop 
100 loops, best of 3: 2.17 ms per loop 

大數據

from string import ascii_letters 

np.random.seed([3,1415]) 
df = pd.DataFrame(
    np.random.randint(10, size=(1000, 52)), 
    pd.Index(['t{:05d}'.format(i) for i in range(1000)], name='Date'), 
    list(ascii_letters) 
).reset_index() 

10 loops, best of 3: 156 ms per loop 
1 loop, best of 3: 3.75 s per loop