Python 从字典到excel表的值

Python 从字典到excel表的值,python,excel,pandas,Python,Excel,Pandas,我有134个节点。已经执行了十四种不同的分析(运行)。对于所有134个节点,每个运行都有保存为字典的值。每个节点都保存了150个时间步的值(每个节点150个值)。例如,运行1保存为字典(10个时间步),即节点A(0,1,0,5,6,7,8,1,0,6)和节点B(1,2,3,4,5,7,6,8,9,1)。类似地,运行2保存为字典。我可以将这些值导出到excel工作表中,但这些值一起保存为(0,1,0,5,6,7,8,1,0,6)。我只希望每个节点的前三个值在三个单独的列中导出到excel工作表(而

我有134个节点。已经执行了十四种不同的分析(运行)。对于所有134个节点,每个运行都有保存为字典的值。每个节点都保存了150个时间步的值(每个节点150个值)。例如,运行1保存为字典(10个时间步),即节点A(0,1,0,5,6,7,8,1,0,6)和节点B(1,2,3,4,5,7,6,8,9,1)。类似地,运行2保存为字典。我可以将这些值导出到excel工作表中,但这些值一起保存为(0,1,0,5,6,7,8,1,0,6)。我只希望每个节点的前三个值在三个单独的列中导出到excel工作表(而不是全部10个值)

如何从运行1和运行2导出每列中的单个值,并将其保存在excel工作表中

代码,用于保存excel工作表,其中所有值列在一列中:

run1, run2, run3, run4, run5, run6, run7, run8, run9, run10, run11, run12, run13, run14 = data # each run has 5 values for 2 variables
 df = pd.DataFrame.from_dict(data)
 df.to_excel("data.xlsx")
当我运行此代码时,
df_1=df.loc[:,pd.indexlice[:,['Value 1','Value 3','Value 5']]

我得到了以下错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-84-8d2d90289161> in <module>()
----> 1 df_1= df.loc[:, pd.IndexSlice[:, ['Value 1', 'Value 3', 'Value 5']]]

/home/MBIAL/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/indexing.py in __getitem__(self, key)
   1308 
   1309         if type(key) is tuple:
-> 1310             return self._getitem_tuple(key)
   1311         else:
   1312             return self._getitem_axis(key, axis=0)

/home/MBIAL/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/indexing.py in _getitem_tuple(self, tup)
    794     def _getitem_tuple(self, tup):
    795         try:
--> 796             return self._getitem_lowerdim(tup)
    797         except IndexingError:
    798             pass

/home/MBIAL/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/indexing.py in _getitem_lowerdim(self, tup)
    920         for i, key in enumerate(tup):
    921             if is_label_like(key) or isinstance(key, tuple):
--> 922                 section = self._getitem_axis(key, axis=i)
    923 
    924                 # we have yielded a scalar ?

/home/MBIAL/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/indexing.py in _getitem_axis(self, key, axis)
   1470                     raise ValueError('Cannot index with multidimensional key')
   1471 
-> 1472                 return self._getitem_iterable(key, axis=axis)
   1473 
   1474             # nested tuple slicing

/home/MBIAL/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/indexing.py in _getitem_iterable(self, key, axis)
   1034     def _getitem_iterable(self, key, axis=0):
   1035         if self._should_validate_iterable(axis):
-> 1036             self._has_valid_type(key, axis)
   1037 
   1038         labels = self.obj._get_axis(axis)

/home/MBIAL/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/indexing.py in _has_valid_type(self, key, axis)
   1390 
   1391             # TODO: don't check the entire key unless necessary
-> 1392             if len(key) and np.all(ax.get_indexer_for(key) < 0):
   1393 
   1394                 raise KeyError("None of [%s] are in the [%s]" %

/home/MBIAL/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/indexes/base.py in get_indexer_for(self, target, **kwargs)
   2384         """ guaranteed return of an indexer even when non-unique """
   2385         if self.is_unique:
-> 2386             return self.get_indexer(target, **kwargs)
   2387         indexer, _ = self.get_indexer_non_unique(target, **kwargs)
   2388         return indexer

/home/MBIAL/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/indexes/base.py in get_indexer(self, target, method, limit, tolerance)
   2284                                  'backfill or nearest reindexing')
   2285 
-> 2286             indexer = self._engine.get_indexer(target._values)
   2287 
   2288         return _ensure_platform_int(indexer)

pandas/index.pyx in pandas.index.IndexEngine.get_indexer (pandas/index.c:6077)()

pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.lookup (pandas/hashtable.c:14050)()

TypeError: unhashable type 
TypeError回溯(最近一次调用)
在()
---->1 df_1=df.loc[:,pd.indexlice[:,['Value 1','Value 3','Value 5']]
/home/MBIAL/enthught/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/index.py in uuuuu getitem_uuuuu(self,key)
1308
1309如果类型(键)为元组:
->1310返回self.\u getitem\u元组(键)
1311其他:
1312返回自身。\u获取项目\u轴(键,轴=0)
/home/MBIAL/enthught/Canopy\u 64bit/User/lib/python2.7/site-packages/pandas/core/index.py in\u getitem\u tuple(self,tup)
794 def_getitem_元组(self,tup):
795尝试:
-->796返回自我。\u getitem\u lowerdim(tup)
797除索引错误外:
798通行证
/home/MBIAL/enthught/canopy64bit/User/lib/python2.7/site-packages/pandas/core/index.py in_getitem_lowerdim(self,tup)
920表示i,输入枚举(tup):
921如果类似于标签(键)或isinstance(键,元组):
-->922节=自。\获取项目\轴(键,轴=i)
923
我们得到了一个标量?
/home/MBIAL/enthught/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/index.py in_getitem_axis(self、key、axis)
1470 raise VALUERROR('无法使用多维键编制索引')
1471
->1472返回自我。\u获取项目\u可编辑(键,轴=轴)
1473
1474#嵌套元组切片
/home/MBIAL/enthught/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/index.py in_getitem_iterable(self、key、axis)
1034定义获取项目可编辑(自身、键、轴=0):
1035如果是自测试,则应验证可测试性(轴):
->1036 self.\u具有有效的\u类型(键、轴)
1037
1038标签=self.obj.\u get\u轴(轴)
/home/MBIAL/enthught/Canopy\u 64bit/User/lib/python2.7/site-packages/pandas/core/index.py in\u具有有效的\u类型(self、key、axis)
1390
1391#待办事项:除非必要,否则不要检查整把钥匙
->1392如果len(key)和np.all(ax.get\u索引器)(key)<0):
1393
1394 raise KeyError(“[%s]中没有一个在[%s]”%
/home/MBIAL/enthught/Canopy\u 64bit/User/lib/python2.7/site-packages/pandas/index/base.py在get\u indexer\u for(self、target、**kwargs)中
2384“即使索引器非唯一,也保证返回”
2385如果self.u是唯一的:
->2386返回自我。获取索引器(目标,**kwargs)
2387索引器,u=self.get_索引器\u非唯一(目标,**kwargs)
2388返回索引器
/get_索引器中的home/MBIAL/enthught/Canopy_64bit/User/lib/python2.7/site-packages/pandas/index/base.py(self、target、method、limit、tolerance)
2284“回填或最近的重新索引”)
2285
->2286索引器=自身引擎。获取索引器(目标值)
2287
2288返回_确保_平台_内部(索引器)
pandas.index.IndexEngine.get_indexer中的pandas/index.pyx(pandas/index.c:6077)()
pandas.hashtable.PyObjectHashTable.lookup中的pandas/src/hashtable\u class\u helper.pxi(pandas/hashtable.c:14050)()
TypeError:不可损坏的类型
多谢各位

Priya

这将有效:

  • 通过以下方式将列中的值列表拆分为多列:

    df[['Value1','Value2','Value3','Value4','Value5','Value6']=pd.DataFrame(df.A.values.tolist(),index=df.index)

  • 选择所需的列:

    df=df['Value1','Value3','Value6']]

  • 写入csv

    将熊猫作为pd导入

    df.to_csv(“Output.csv”)

  • 这将有助于:

  • 通过以下方式将列中的值列表拆分为多列:

    df[['Value1','Value2','Value3','Value4','Value5','Value6']=pd.DataFrame(df.A.values.tolist(),index=df.index)

  • 选择所需的列:

    df=df['Value1','Value3','Value6']]

  • 写入csv

    将熊猫作为pd导入

    df.to_csv(“Output.csv”)


  • 使用字典理解,然后按以下方式筛选列中的
    多索引


    使用字典理解,然后按以下方式筛选列中的
    多索引


    由于没有值的标题,我使用以下代码找到了我感兴趣的节点的值位置:

    df_1=df_1.iloc[:,[Node 1]]

    运行此代码时,它会给出节点1的开始和停止位置。所以我在上面由jezrael提供的代码中给出了这一行,并将结果保存到excel工作表中

    将jezrael代码中的下一行替换为上一行:

    df=df.loc[:,pd.indexlice[:,['Value 1','Value 3','Value 5']]


    @jezrael和Rahul Agarwal感谢您提供的所有帮助

    因为我没有指向值的标题,我找到了我感兴趣的节点的值位置
    #python 3.6 +
    f = lambda x: f'Value {x + 1}'
    #python bellow 3.6
    #f = lambda x: 'Value {}'.format(x + 1)
    d = {x: pd.DataFrame(df[x].values.tolist(), index=df.index).rename(columns=f) 
            for x in df.columns}
    df = pd.concat(d, axis=1)
    
    df = df.loc[:, pd.IndexSlice[:, ['Value 1','Value 3','Value 5']]]
    print (df)
                A                       B                
          Value 1 Value 3 Value 5 Value 1 Value 3 Value 5
    Run 1       0       0       6       1       3       5
    Run 2       0       0       1       1       3       0
    
    df.to_excel(file)