熊猫数据框读取numpy数组列为str

时间:2019-02-10 08:22:01

标签: python pandas numpy

我有两个Python脚本,一个用于创建 const data = [ { hours: "6", type: "Welding", identifier: "-LYIaWAxkQA38DAbC3By", id: 1 }, { hours: "2", type: "Hair Drying", identifier: "-LYIab-Ys9WkUNHE2cqL", id: 2 } ] <FlatList data=data renderItem={ (item) => <Text>{item.type}</Text> } keyExtractor={(item, index) => item.id.toString()} /> 文件,另一个用于读取文件。

这是我将数据框保存在第一个文件中的方式:

.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)

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

如何确保type of df['matrix'].iloc[0] <class 'str'>不会失去其性质?

2 个答案:

答案 0 :(得分:1)

如果要保存和只读numpy数组,请使用savetxtgenfromtxt


如果有多列,请使用:

使用pickle

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'>

答案 1 :(得分:1)

要使用多个列将数组直接保存到csv,请使用:

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

如果您需要作为python对象读回,{@ {1}}是@jezrael指出的救星

相关问题