如何在 python 中转换'one' csv 文件单元格中保存为字符串的数字数组?


p[1:2]
Out[23]: 
array([['[0.7856142  0.77921445 0.8273963  0.86992871 0.82833104 0.80677249n 0.8410951  0.90299239 0.82401068 0.78761172 0.81294067 0.81446944]']],
dtype=object)

这是我从 df.iloc[].values from cell 获得的数据之一。Spyder 变量资源管理器 说: 类型: numpy 的 ndarray 对象。我想转换为正确的数字数组。我做得有多大声?我用过p1=np.asfarray(p[1:2],float)p1=pd.to_numeric(p[1:2], downcast = 'float')它显示 raise TypeError。

我可能会使用列表理解:

In [11]: [[float(x) for x in item[1:-1].split()] for row in a for item in row]
Out[11]:
[[0.7856142,
0.77921445,
0.8273963,
0.86992871,
0.82833104,
0.80677249,
0.8410951,
0.90299239,
0.82401068,
0.78761172,
0.81294067,
0.81446944]]

将来,您可能希望使用 JSON 序列化而不是 .values 的字符串。例如:

In [21]: df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
In [22]: df.to_json()
Out[22]: '{"A":{"0":1,"1":3},"B":{"0":2,"1":4}}'

这样你就可以在另一边pd.read_json

相关内容

最新更新