如何在csv中保存2d关联数组而不循环?

时间:2019-10-26 06:58:18

标签: python pandas dataframe

我有一个2维关联数组,如下所示:

import numpy as np
import pandas as pd

stateList = ['0_0_0', '0_0_1', '0_0_2', '0_0_3']
toState          = { state : 0  for state in stateList}
transitionCounter = { state : toState.copy()  for state in stateList}

transitionCounter['0_0_0']['0_0_2'] = 1
transitionCounter['0_0_0']['0_0_0'] = 10
transitionCounter['0_0_3']['0_0_2'] = 4

transitionCounter['0_0_1']['0_0_2'] = 5
transitionCounter['0_0_3']['0_0_1'] = 7

print(transitionCounter)

但是,现在我希望将其保存为.csv文件。因此,其最终格式应为:

enter image description here

我尝试了以下代码:

stateColumn = ['0_0_0', '0_0_1', '0_0_2', '0_0_3']
dt = pd.DataFrame(columns=stateColumn)
dt["States"] = ['0_0_0', '0_0_1', '0_0_2', '0_0_3']

print(dt)

for fromState in stateList:
    for toState in stateList:
        dt[dt["States"] == fromState,toState] = transitionCounter[fromState][toState]

但是它抱怨以下错误:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

2 个答案:

答案 0 :(得分:0)

您可以使用.csv将数组写入csv.writer(...)文件。

例如:

...
import csv

...

with open("new_file.csv","w+") as file:
    csvWriter = csv.writer(file,delimiter=',')
    csvWriter.writerows(transitionCounter)

答案 1 :(得分:0)

要通过字典创建DataFrame,您可以简单地使用:

dt = pd.DataFrame(transitionCounter).T

结果:

       0_0_0  0_0_1  0_0_2  0_0_3
0_0_0     10      0      1      0
0_0_1      0      0      5      0
0_0_2      0      0      0      0
0_0_3      0      7      4      0

要将数据集另存为csv文件,可以使用函数to_csv()

dt.to_csv('file_name.csv')

要解决for循环中的错误,您需要添加属性loc

for fromState in stateList:
    for toState in stateList:
        dt.loc[dt["States"] == fromState,toState] = transitionCounter[fromState][toState]