python - 从 python 中的 numpy genfromtxt 获取列名

标签 python numpy genfromtxt

在python中使用numpy genfromtxt,我希望能够获取列标题作为给定数据的键。我尝试了以下方法,但无法获取相应数据的列名。

column = np.genfromtxt(pathToFile,dtype=str,delimiter=',',usecols=(0))
columnData = np.genfromtxt(pathToFile,dtype=str,delimiter=',')
data = dict(zip(column,columnData.tolist()))

下面是数据文件

header0,header1,header2
mydate,3.4,2.0
nextdate,4,6
afterthat,7,8

目前,它显示的数据为

{
  "mydate": [
    "mydate",
    "3.4",
    "2.0"
  ],
  "nextdate": [
    "nextdate",
    "4",
    "6"
  ],
  "afterthat": [
    "afterthat",
    "7",
    "8"
  ]
}

我想采用这种格式

{
  "mydate": {
    "header1":"3.4",
    "header2":"2.0"
  },
  "nextdate": {
    "header1":"4",
    "header2":"6"
  },
  "afterthat": {
   "header1":"7",
   "header2":  "8"
  }
}

有什么建议吗?

最佳答案

使用 pandas 模块:

In [94]: fn = r'D:\temp\.data\z.csv'

将 CSV 读入数据框:

In [95]: df = pd.read_csv(fn)

In [96]: df
Out[96]:
     header0  header1  header2
0     mydate      3.4      2.0
1   nextdate      4.0      6.0
2  afterthat      7.0      8.0

获取所需的字典:

In [97]: df.set_index('header0').to_dict('index')
Out[97]:
{'afterthat': {'header1': 7.0, 'header2': 8.0},
 'mydate': {'header1': 3.3999999999999999, 'header2': 2.0},
 'nextdate': {'header1': 4.0, 'header2': 6.0}}

或作为 JSON 字符串:

In [107]: df.set_index('header0').to_json(orient='index')
Out[107]: '{"mydate":{"header1":3.4,"header2":2.0},"nextdate":{"header1":4.0,"header2":6.0},"afterthat":{"header1":7.0,"header2":8.0}}'

关于python - 从 python 中的 numpy genfromtxt 获取列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39216092/

相关文章:

python - 如何集成 Python mido 和 asyncio?

Python - 加载大量图像而不使用所有可用的内存

python - 根据 numpy 数组中的行生成唯一值

python - 导入函数参数 numpy

python - 使用 try except 时递归打印异常详细信息

python - 编写检查所有 pandas DataFrame 列值是否满足特定值?

python - 当我通过 early_stopping_rounds 时 XGBClassifier 失败

numpy - Scipy.optimize - 使用固定参数进行曲线拟合

python - 如何将 CSV 数据读入 NumPy 中的记录数组?

python - 如何显示不带引号且以逗号作为分隔符的 NumPy 字符串数组?