簡體   English   中英

熊貓數據框讀取numpy數組列為str

[英]Pandas dataframe reading numpy array column as str

我有兩個Python腳本,一個用於創建.csv文件,另一個用於讀取文件。

這就是我將數據框保存在第一個文件中的方式:

df['matrix'] = df['matrix'].apply(lambda x: np.array(x))
df.to_csv("Matrices.csv", sep=",", index=False)

df['matrix'].iloc[0]的類型和形狀分別為<class 'numpy.ndarray'>(24, 60) <class 'numpy.ndarray'> (24, 60)

在第二個腳本中,當我嘗試

print ("type of df['matrix'].iloc[0]", type(df['matrix'].iloc[0]))

輸出為type of df['matrix'].iloc[0] <class 'str'>

如何確定df['matrix']不會失去其性質?

如果要保存並僅讀取numpy數組,請使用savetxtgenfromtxt


如果有多個列,請使用:

使用泡菜

df.to_pickle('file.pkl')
df = pd.read_pickle('file.pkl')

將數組轉換為多列,然后寫入文件:

a = np.array(
[[219,220,221],
 [154,152,14],
 [205,202,192]])

df = pd.DataFrame({'matrix':a.tolist(), 'b':np.arange(len(a))})
print (df)
            matrix  b
0  [219, 220, 221]  0
1   [154, 152, 14]  1
2  [205, 202, 192]  2

df1 = pd.DataFrame(df.pop('matrix').values.tolist(), index=df.index).add_prefix('mat_')
print (df1)
   mat_0  mat_1  mat_2
0    219    220    221
1    154    152     14
2    205    202    192

df = df.join(df1)
print (df)
   b  mat_0  mat_1  mat_2
0  0    219    220    221
1  1    154    152     14
2  2    205    202    192

但是,如果真的需要將值轉換為array需要使用ast.literal_eval轉換器:

import ast

df.to_csv('testing.csv', index=False)

df = pd.read_csv('testing.csv', converters={'matrix':lambda x: np.array(ast.literal_eval(x))})
print (type(df.loc[0, 'matrix']))

<class 'numpy.ndarray'>

要將數組作為多列直接保存到csv中,請使用:

np.savetxt(r'C:\path\file.csv',a,delimiter=',')

如果您需要以python對象的形式讀取,則ast.literal_eval()是@jezrael指出的救星

暫無
暫無

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

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