【问题标题】:How to convert array of numbers saved as string in 'one' cell of a csv file in python?如何在python中的csv文件的“一个”单元格中转换保存为字符串的数字数组?
【发布时间】:2018-11-11 21:27:31
【问题描述】:
p[1:2]
Out[23]: 
array([['[0.7856142  0.77921445 0.8273963  0.86992871 0.82833104 0.80677249\n 0.8410951  0.90299239 0.82401068 0.78761172 0.81294067 0.81446944]']],
      dtype=object)

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

【问题讨论】:

    标签: arrays python-3.x pandas csv numpy


    【解决方案1】:

    我可能会使用列表推导:

    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

    【讨论】:

      猜你喜欢
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多