【发布时间】:2021-04-02 01:09:22
【问题描述】:
我正在将我的 Pandas DataFrame 格式化为机器学习模型所需的格式。
预处理步骤中最令人沮丧的任务之一是将 DataFrame 行高效地转换为列名和值组合的列表
我的 DataFrame 中的两行示例如下所示:
index | userID | col1 | col2 | col3 ... col10000
0 123 0 1 0 1
1 456 1 1 0 0
所需格式是元组列表,其中第一个值是用户 ID,第二个值是包含其余列名及其值的组合的列表,例如:
[(123, ['col1:0', 'col2:1', 'col3:0',...., 'col10000:1'])
,(456, ['col1:1', 'col2:1', 'col3:0',...., 'col10000:0'])]
我已经尝试过并行化 apply 但是 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 pandas performance dataframe vectorization