我在拥有2500万条记录的pandas数据框中有非常稀疏的数据。这必须转换为多维numpy数组。我使用for
循环以直截了当的方式编写了这个,并且想知道是否有更有效的方法。
import numpy as np
import pandas as pd
facts_pd = pd.DataFrame.from_records(columns=['name','offset','code'],
data=[('John', -928, 'dx_434'), ('Steve',-757,'dx_5859'), ('Jack',-800,'dx_250'),
('John',-919,'dx_401'),('John',-956,'dx_5859')])
name_lu = pd.DataFrame(sorted(facts_pd['name'].unique()), columns=['name'])
name_lu["nameid"] = name_lu.index
offset_lu = pd.DataFrame(sorted(facts_pd['offset'].unique(), reverse=True), columns=['offset'])
offset_lu["offsetid"] = offset_lu.index
code_lu = pd.DataFrame(sorted(facts_pd['code'].unique()), columns=['code'])
code_lu["codeid"] = code_lu.index
facts_pd = pd.merge(pd.merge(pd.merge(facts_pd, name_lu, how="left", on="name")
, offset_lu, how="left", on="offset"), code_lu, how="left", on="code")
facts_pd.drop(["name","offset","code"], inplace=True, axis=1)
facts_np = np.zeros((len(name_lu),len(offset_lu),len(code_lu)))
for row in facts_pd.iterrows():
i,j,k = row[1]
facts_np[i][j][k] = 1
答案 0 :(得分:0)
答案 1 :(得分:-1)
将numpy导入为np
将pandas导入为pd
facts_pd = pd.DataFrame.from_records(columns = [' name',' offset',' code'], data = [(' John',-928,' dx_434'),(' Steve', - 757,' dx_5859'),( '杰克', - 800,' dx_250&#39), ('约翰', - 919,' dx_401&#39),('约翰', - 956,' dx_5859&#39)])
facts_np = facts_pd.as_matrix()
print facts_np#以numpy数组格式显示数据帧。