【发布时间】:2017-03-05 04:54:00
【问题描述】:
我正在尝试从一个 .npy 文件中创建一个 pandas 数据帧,当使用 np.load 读取该文件时,它会返回一个包含字典的 numpy 数组。我最初的直觉是提取字典,然后使用 pd.from_dict 创建一个数据框,但这每次都失败,因为我似乎无法从 np.load 返回的数组中取出字典。看起来它只是 np.array([dictionary, dtype=object]),但我无法通过索引数组或类似的东西来获取字典。我也尝试过使用 np.load('filename').item() 但结果仍然无法被 pandas 识别为字典。
或者,我尝试了 pd.read_pickle ,但也没有用。
如何将这个 .npy 字典放入我的数据框中?这是一直失败的代码...
import pandas as pd
import numpy as np
import os
targetdir = '../test_dir/'
filenames = []
successful = []
unsuccessful = []
for dirs, subdirs, files in os.walk(targetdir):
for name in files:
filenames.append(name)
path_to_use = os.path.join(dirs, name)
if path_to_use.endswith('.npy'):
try:
file_dict = np.load(path_to_use).item()
df = pd.from_dict(file_dict)
#df = pd.read_pickle(path_to_use)
successful.append(path_to_use)
except:
unsuccessful.append(path_to_use)
continue
print str(len(successful)) + " files were loaded successfully!"
print "The following files were not loaded:"
for item in unsuccessful:
print item + "\n"
print df
【问题讨论】:
-
您是如何创建
.npy文件的?是否使用np.save() -
不幸的是,它只是给了我。有人告诉我,我可以使用 np.load 从中得到我需要的东西。
-
不应该是
pd.DataFrame.from_dict而不是pd.from_dict吗?至少在pandas 0.18.1中,后者不存在。无论哪种方式,您确定问题出在.npy文件上吗?我可以使用np.save和np.load成功保存和加载字典。您能否发布有关file_dict的详细信息以及错误消息? -
你是对的 pd.DataFrame.from_dict()!但是,当我给出参数 x where x = np.load(path_to_use).item() 时,我收到一条错误消息,提示“异常:数据必须是一维的”。 Here's 打印 x 时看到的一小部分。
标签: python pandas dictionary pickle