我正在将Pandas DataFrame格式化为机器学习模型所需的格式。
预处理步骤中最令人沮丧的任务之一是将DataFrame行高效地转换为列名和值组合的列表
我的DataFrame中有两行的示例如下:
index | userID | col1 | col2 | col3 ... col10000
0 123 0 1 0 1
1 456 1 1 0 0
所需的格式是元组列表,其中第一个值是userID,第二个值是包含其余列名及其值的组合的列表,例如:
[(123, ['col1:0', 'col2:1', 'col3:0',...., 'col10000:1'])
,(456, ['col1:1', 'col2:1', 'col3:0',...., 'col10000:0'])]
我已经尝试过并行化apply,但apply方法仍然很慢,并且并行化会导致内存问题。尝试的应用方法:
def add_features(row):
return ((int(row.iloc[0]),(",".join(["%s:%s"%(x,y) for x,y in row[row.index[1:]].items()]).split(","))))
def apply_add_features(df):
df['features_formatted'] = df.apply(add_features, axis=1)
return df['features_formatted']
apply_add_features(df)
有人能帮忙吗?
您只需对数据帧执行此操作,请注意,我首先将数据帧转换为python dictionations。。,这可以更有效地改变形状(如果内存问题得到解决,请告诉我(:示例数据帧
df = pd.DataFrame({'userID':np.arange(0,100,10),'a':np.arange(10),'b':np.arange(10)})
userID a b
0 0 0 0
1 10 1 1
2 20 2 2
3 30 3 3
4 40 4 4
5 50 5 5
6 60 6 6
7 70 7 7
8 80 8 8
9 90 9 9
获取结果的代码:
df = df.set_index('userID')
data =[(k,[f"{k2}:{v}" for k2,v in d.items()]) for k,d in df.to_dict('index').items()]
>>> data
[(0, ['a:0', 'b:0']),
(10, ['a:1', 'b:1']),
(20, ['a:2', 'b:2']),
(30, ['a:3', 'b:3']),
(40, ['a:4', 'b:4']),
(50, ['a:5', 'b:5']),
(60, ['a:6', 'b:6']),
(70, ['a:7', 'b:7']),
(80, ['a:8', 'b:8']),
(90, ['a:9', 'b:9'])]