2017-10-10 55 views
0

我有一些数据(42特征)在几个月内收集的人(最大-6; 因不同条目而异),每个月的价值是自己的行:构建一个从每个索引值的多个附加

enter image description here

有9267倍唯一ID的值(设定为索引)和多达50 000行的DF。 我想将其转换为42个* 6的特征向量每个ID(即使有些会有很多的NaN存在的),这样我可以在训练他们,这里是应该的样子:

enter image description here

这里是我的解决方案:

def flatten_features(f_matrix, ID): 
    '''constructs a 1x(6*n) vector from 6xn matrix''' 
    #check wether it is a series, not dataframe 
    if(len(f_matrix.shape) == 1): 
     f_matrix['ID'] = ID 
     return f_matrix 

    flattened_vector = f_matrix.iloc[0] 

    for i in range(1, f_matrix.shape[0]): 
     vector_append = f_matrix.iloc[i] 
     vector_append.index = (lambda month, series_names : series_names.map(lambda name : name + '_' + str(month)))\ 
           (i, vector_append.index) 
     flattened_vector = flattened_vector.append(vector_append) 

    flattened_vector['ID'] = ID 
    return flattened_vector 


#construct dataframe of flattened vectors for numerical features 
new_indices = flatten_features(numerical_f.iloc[:6], 1).index 
new_indices 

flattened_num_f = pd.DataFrame(columns=new_indices) 
flattened_num_f 

for label in numerical_f.index.unique(): 

    matr = numerical_f.loc[label] 
    flattened_num_f = flattened_num_f.append(flatten_features(matr, label)) 

它产生所需的结果,但它的运行速度非常慢。我想知道,是否有更优雅和快速的解决方案?

+0

这完全是我不清楚你的期望的输出是什么ID。你能举出你的输入例子吗?**不是图像**和期望的输出? –

+0

@ juanpa.arrivillaga我应该如何显示我输入的巨大df,如果不是通过jupyter笔记本表示的方式? – TheSmokingGnu

+0

根据需要提供[mcve]。一个图像是无用的。看看[这个问题](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)关于如何创建一个好的,可重复的'pandas'例子。 –

回答

0

如果你想转置df,你可以凸轮T功能。 我假设你已经存储在UNIQUE_ID可变

new_f = numerical_f.T 
new_f.columns = unique_id 
+0

但是转置后的矩阵会有〜50 000列,而你的第二行只是用〜9000行替换它们,这会导致错误 – TheSmokingGnu

+0

@ TheSmokingGnu你想把所有相同的id聚合在一起吗? – galaxyan

+0

是的,每个唯一ID有1 42 * 6的二维行,包含这个ID的最多六行的值(全部存在) – TheSmokingGnu