【问题标题】:Outputting dataframes to csv using a loop使用循环将数据帧输出到 csv
【发布时间】:2013-03-07 07:23:13
【问题描述】:

我有从数据框构建的组并试图理解为什么这不起作用:

for i in range(1,12):
  out1=df.ix['group%s'% i]
  out1.to_csv('group%s.csv' % i)
  out1.pl.describe()

group_i 的一个例子是: (a,b 包含浮点数)

group1=df["ptdelta"][a & b]
a=df["ptdelta"]>=0
b=df["ptdelta"]<5 

回溯给出 KeyError: group1 (表示第一次尝试)

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-87-11399ea315df> in <module>()
      6 '''
      7 for i in range(1,12):
----> 8   out1=df.ix['group%s'% i]
      9   out1.to_csv('group%s.csv' %i)
     10   out1.pl.describe()

 C:\Python27\lib\site-packages\pandas\core\indexing.pyc in __getitem__(self, key)
     32             return self._getitem_tuple(key)
     33         else:
 ---> 34             return self._getitem_axis(key, axis=0)
     35 
     36     def _get_label(self, label, axis=0):

C:\Python27\lib\site-packages\pandas\core\indexing.pyc in _getitem_axis(self, key, axis)
    343                     return self._get_loc(key, axis=0)
    344 
--> 345             return self._get_label(idx, axis=0)
    346         else:
    347             labels = self.obj._get_axis(axis)

【问题讨论】:

    标签: python-2.7 pandas


    【解决方案1】:

    您正在尝试使用字符串值“组”进行索引,该值在您的数据框中不是有效索引。如果您的列表中已经有多个组,并且每个组都是具有正确大小索引的系列,您可以尝试:

    i = 1
    for group in groups:
        out1=df.ix[group]
        out1.to_csv('group%s.csv' % i)
        out1.pl.describe()
        i += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-10
      • 2014-08-13
      • 1970-01-01
      • 2020-03-29
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多