Skip to main content
 首页 » 编程设计

python之Pandas 数据帧 : how to build them efficiently

2025年02月15日25yxwkf

我有一个包含 1M 行的文件,我正在尝试将其读入 20 个 DataFrame。我事先不知道哪一行属于哪个 DataFrame 或每个 DataFrame 有多大。我怎样才能有效地将这个文件处理成数据帧?我试过用几种不同的方法来做到这一点。这是我目前拥有的:

data = pd.read_csv(r'train.data', sep=" ", header = None) # Not slow 
def collectData(row): 
    id = row[0] 
    df = dictionary[id] # Row content determines which dataframe this row belongs to 
    next = len(df.index) 
    df.loc[next] = row 
data.apply(collectData, axis=1) 

速度很慢。我究竟做错了什么?如果我只应用一个空函数,我的代码将在 30 秒内运行。实际功能至少需要 10 分钟,我不确定它是否完成。

以下是数据集中的一些示例行:

1 1 4 
1 2 2 
1 3 10 
1 4 4 

完整的数据集可用here (如果你点击Matlab版本)

请您参考如下方法:

您的方法不是矢量方法,因为您逐行应用了一个 Python 函数。

与其创建 20 个数据帧,不如为每个键 [0] 创建一个包含索引(在范围 (20) 内)的字典。然后将此信息添加到您的 DataFrame 中:

 data['dict']=data[0].map(dictionary) 

然后重组:

 data2=data.reset_index().set_index(['dict','index']) 

data2 就像:

            0  1   2 
dict index           
12   0      1  1   4 
     1      1  2   2 
     2      1  3  10 
     3      1  4   4  
     4      1  5   2 
     .... 

和 data2.loc[i] 是您想要的 Dataframe 之一。

编辑:

train.label 中似乎描述了字典。

您可以通过以下方式设置字典:

with open(r'train.label') as f: u=f.readlines() 
v=[int(x) for x in u] # len(v) = 11269 = data[0].max() 
dictionary=dict(zip(range(1,len(v)+1),v))