簡體   English   中英

從.npy文件制作熊貓數據框

[英]Making a pandas dataframe from a .npy file

我正在嘗試從.npy文件制作一個熊貓數據幀,當使用np.load讀取時,它返回一個包含字典的numpy數組。 我的最初本能是提取字典,然后使用pd.from_dict創建一個數據框,但是每次都會失敗,因為我似乎無法從np.load返回的數組中取出字典。 看起來它只是np.array([dictionary,dtype = object]),但是我無法通過索引數組或類似的東西來獲取字典。 我也嘗試過使用np.load('filename')。item(),但結果仍未被熊貓識別為字典。

另外,我嘗試了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.load(path_to_use).item() )看起來與此類似;

{'user_c': 'id_003', 'user_a': 'id_001', 'user_b': 'id_002'}

因此,如果您需要使用上面的字典來提供如下所示的DataFrame;

  user_name user_id
0    user_c  id_003
1    user_a  id_001
2    user_b  id_002

您可以使用;

df = pd.DataFrame(list(x.item().iteritems()), columns=['user_name','user_id'])

如果您有類似以下的詞典列表;

users = [{'u_name': 'user_a', 'u_id': 'id_001'}, {'u_name': 'user_b', 'u_id': 'id_002'}]

您可以簡單地使用

df = pd.DataFrame(users)

提出類似的DataFrame;

     u_id  u_name
0  id_001  user_a
1  id_002  user_b

好像您有一本與此類似的字典;

data = {
    'Center': [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]],
    'Vpeak': [1.1, 2.2],
    'ID': ['id_001', 'id_002']
}

在這種情況下,您可以簡單地使用;

df = pd.DataFrame(data)  # df = pd.DataFrame(file_dict.item()) in your case

提出類似的DataFrame;

    Center          ID      Vpeak
0   [0.1, 0.2, 0.3] id_001  1.1
1   [0.4, 0.5, 0.6] id_002  2.2

如果字典中包含ndarray ,請執行以下類似的預處理; 並使用它創建df;

for key in data:
    if isinstance(data[key], np.ndarray):
        data[key] = data[key].tolist()

df = pd.DataFrame(data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM