【问题标题】:Is it possible to save/export a reshaped data using pandas into csv/text/h5 file?是否可以使用 pandas 将重塑的数据保存/导出到 csv/text/h5 文件中?
【发布时间】:2017-06-28 08:09:24
【问题描述】:

我发现了这个问题:How to reshape every nth row's data using pandas?

我修改了脚本以将结果保存在 csv 文件中,但出现错误提示

AttributeError: 'numpy.ndarray' object has no attribute 'to_csv'

这是脚本。基本上我只是添加了

to_csv()

给它。

import pandas as pd

df = pd.read_csv("test.csv")

start = 0
for i in range(0, len(df.index)):
    if (i + 1)%10 == 0:
        result = df['Break'].iloc[start:i+1].reshape(2,5)
        start = i + 1

        result.to_csv('testing.csv')

我的问题是是否可以像这样保存结果

[['ww' 'ee' 'qq' 'xx' 'dd']
 ['gg' 'hh' 'tt' 'yy' 'uu']]
[['ii' 'oo' 'pp' 'mm' 'ww']
 ['zz' 'cc' 'rr' 'tt' 'll']] 

作为 csv 文件?

根据我从结果中看到的,'ww' 直到 'uu'(第一个矩阵)可以被认为是第一行,而第二个矩阵('ii' until 'll')可以被认为是第二行,这可以导出为 csv 文件(或其他文件格式;h5 或文本)

感谢您的帮助。

[更新]

我已经查看了可能的重复问题,但我认为我的问题有点不同,因为另一个问题显示输出是这样的

[ 266.77832991  201.06347505  446.00066136  499.76736079  295.15519906
  214.50514991  422.1043505   531.13126879  287.68760191  201.06347505
  402.68859792  478.85808879  286.19408248  192.10235848]

虽然我是这样的

[['ww' 'ee' 'qq' 'xx' 'dd']
 ['gg' 'hh' 'tt' 'yy' 'uu']]
[['ii' 'oo' 'pp' 'mm' 'ww']
 ['zz' 'cc' 'rr' 'tt' 'll']]

我也尝试了那里提供的答案,但有错误。 这是我尝试过的

import pandas as pd
import numpy as np

df = pd.read_csv("test.csv")

start = 0
for i in range(0, len(df.index)):
    if (i + 1)%10 == 0:
        result = df['Break'].iloc[start:i+1].reshape(2,5)
        start = i + 1
        save = np.savetxt('testing.csv', result, delimiter=' , ')

还有错误

TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e , %.18e , %.18e , %.18e , %.18e')

【问题讨论】:

  • 谢谢@VaishaliGarg 我已经看过一个问题,但我认为我的问题有点不同。我已经更新了我的问题以反映这一点。

标签: python csv pandas h5py


【解决方案1】:

给定一个像这样的 numpy 数组

a = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ])

您可以像这样将其保存为 csv 文件

numpy.savetxt("foo.csv", a, delimiter=",")

生成的文件 foo.csv 具有所需的格式。

回复here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    相关资源
    最近更新 更多