我有一些数据(42特征)在几个月内收集的人(最大-6; 因不同条目而异),每个月的价值是自己的行:构建一个从每个索引值的多个附加
有9267倍唯一ID的值(设定为索引)和多达50 000行的DF。 我想将其转换为42个* 6的特征向量每个ID(即使有些会有很多的NaN存在的),这样我可以在训练他们,这里是应该的样子:
这里是我的解决方案:
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))
它产生所需的结果,但它的运行速度非常慢。我想知道,是否有更优雅和快速的解决方案?
这完全是我不清楚你的期望的输出是什么ID。你能举出你的输入例子吗?**不是图像**和期望的输出? –
@ juanpa.arrivillaga我应该如何显示我输入的巨大df,如果不是通过jupyter笔记本表示的方式? – TheSmokingGnu
根据需要提供[mcve]。一个图像是无用的。看看[这个问题](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)关于如何创建一个好的,可重复的'pandas'例子。 –