【问题标题】:list of column labels as variable to keyword作为关键字变量的列标签列表
【发布时间】:2019-06-29 21:11:09
【问题描述】:

我正在使用 Pandas 数据框对数据表执行操作。根据列中的值,需要写入四种类型的输出 csv 文件。我可以列出要写入 csv 的列标题,但不能将列表传递给 df.to_csv('filename.csv', columns=['fixed1', 'fixed2', variable_list])。我不想写出所有条件的所有列标题。我有中间计算的列,所以我不想将所有列都写入 csv。

我尝试创建标题列表并将子集传递给 df.to_csv,但失败了。

headers = list(df_subset.columns.values)
variable_list = [header for header in headers if header.startswith('foo:')]
print variable_list
df_subset.to_csv('filename.csv', mode= 'w', columns=['fixed1','fixed2', variable_list)

对于一次条件,我希望 csv 输出具有列 fixed1、fix2、foo:1、foo:2,对于另一个条件,我希望 csv 具有列 fixed1、fixed2、foo:3、foo:4、foo:5

print 语句给出子集列表,但 df 方法失败。

['foo:1','foo:2']

File "multifas_trim.py", line 332, in main
    index=False)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 1744, in to_csv
    escapechar=escapechar, decimal=decimal)
  File "/usr/local/lib/python2.7/dist-packages/pandas/io/formats/csvs.py", line 85, in __init__
    self.obj = self.obj.loc[:, cols]
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/indexing.py", line 1472, in __getitem__
    return self._getitem_tuple(key)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/indexing.py", line 875, in _getitem_tuple
    self._has_valid_tuple(tup)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/indexing.py", line 226, in _has_valid_tuple
    .format(types=self._valid_types))
ValueError: Location based indexing can only have [labels (MUST BE IN THE INDEX), slices of labels (BOTH endpoints included! Can be slices of integers if the index is integers), listlike of labels, boolean] types````

【问题讨论】:

    标签: pandas


    【解决方案1】:

    你得到一个嵌套的['fixed1', 'fixed2', ['foo:1', 'foo:2']],你想要的是一个平面列表。也就是说,你会想要做

    columns=['fixed1', 'fixed2'] + variable_list
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-06
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 2022-11-18
      相关资源
      最近更新 更多