Pandas通过一列将CSV分割成多个CSV's(或DataFrames)。[英] Pandas split CSV into multiple CSV's (or DataFrames) by a column

本文是小编为大家收集整理的关于Pandas通过一列将CSV分割成多个CSV's(或DataFrames)。的处理方法,想解了Pandas通过一列将CSV分割成多个CSV's(或DataFrames)。的问题怎么解决?Pandas通过一列将CSV分割成多个CSV's(或DataFrames)。问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我对一个问题感到非常迷失,并且会感激一些帮助或提示.

问题:我已经有一个带有多个值的列的CSV文件,例如:

Fruit;Color;The_evil_column
Apple;Red;something1
Apple;Green;something1
Orange;Orange;something1
Orange;Green;something2
Apple;Red;something2
Apple;Red;something3

我已经将数据加载到数据框中,我需要根据" the_evil_column"的值将该数据框架分为多个数据范围:

df1
Fruit;Color;The_evil_column
Apple;Red;something1
Apple;Green;something1
Orange;Orange;something1

df2
Fruit;Color;The_evil_column
Orange;Green;something2
Apple;Red;something2

df3
Fruit;Color;The_evil_column
Apple;Red;something3

阅读了一些帖子后,我更加困惑,我需要一些提示.

推荐答案

您可以生成数据框字典:

d = {g:x for g,x in df.groupby('The_evil_column')}

In [95]: d.keys()
Out[95]: dict_keys(['something1', 'something2', 'something3'])

In [96]: d['something1']
Out[96]:
    Fruit   Color The_evil_column
0   Apple     Red      something1
1   Apple   Green      something1
2  Orange  Orange      something1

或数据框列表:

In [103]: l = [x for _,x in df.groupby('The_evil_column')]

In [104]: l[0]
Out[104]:
    Fruit   Color The_evil_column
0   Apple     Red      something1
1   Apple   Green      something1
2  Orange  Orange      something1

In [105]: l[1]
Out[105]:
    Fruit  Color The_evil_column
3  Orange  Green      something2
4   Apple    Red      something2

In [106]: l[2]
Out[106]:
   Fruit Color The_evil_column
5  Apple   Red      something3

更新:

In [111]: g = pd.read_csv(filename, sep=';').groupby('The_evil_column')

In [112]: g.ngroups   # number of unique values in the `The_evil_column` column
Out[112]: 3

In [113]: g.apply(lambda x: x.to_csv(r'c:\temp\{}.csv'.format(x.name)))
Out[113]:
Empty DataFrame
Columns: []
Index: []

将产生3个文件:

In [115]: glob.glob(r'c:\temp\something*.csv')
Out[115]:
['c:\\temp\\something1.csv',
 'c:\\temp\\something2.csv',
 'c:\\temp\\something3.csv']

其他推荐答案

您只需通过列的值过滤框架:

frame=pd.read_csv('file.csv',delimiter=';')
frame['The_evil_column']=='something1'

此返回:

0     True
1     True
2     True
3    False
4    False
5    False
Name: The_evil_column, dtype: bool

因此,您访问以下列:

frame1 = frame[frame['The_evil_column']=='something1']

稍后您可以删除列:

frame1 = frame1.drop('The_evil_column', axis=1)

其他推荐答案

更简单但效率较低的方法是:

data = pd.read_csv('input.csv')

out = []

for evil_element in list(set(list(data['The_evil_column']))):
    out.append(data[data['The_evil_column']==evil_element])

out将具有所有数据范围的列表.

本文地址:https://www.itbaoku.cn/post/1728017.html