我正在使用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)
对于一次条件,我希望具有固定列,固定2,foo:1,foo:2的csv输出,对于另一个条件,我希望具有固定列,fixed2,foo:3,foo:4,foo:5的csv输出
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````
答案 0 :(得分:0)
您将获得一个嵌套的['fixed1', 'fixed2', ['foo:1', 'foo:2']]
,其中您想要的是一个平面列表。也就是说,您将要做
columns=['fixed1', 'fixed2'] + variable_list