Bin值基于带有pandas的范围

时间:2015-07-31 01:23:31

标签: python csv numpy pandas

我在文件夹中有多个CSV文件,其值如下:

GroupID.csv是文件名。有这样的多个文件,但值范围在同一XML文件中定义。我试图将它们分组 我怎么能这样做?

UPDATE1: 根据BobHaffner的评论,我已经完成了这个

import pandas as pd 
import glob path =r'path/to/files' 
allFiles = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
list_ = []
for file_ in allFiles:
    df = pd.read_csv(file_,index_col=None, header=None)
    df['file'] = os.path.basename('path/to/files/'+file_)
    list_.append(df)
frame = pd.concat(list_)
print frame

得到这样的东西:

我需要根据XML文件中的bin对值进行分组。我真的很感激任何帮助。

1 个答案:

答案 0 :(得分:36)

为了打开你的系列,你应该使用the pd.cut() function,如下所示:

df['bin'] = pd.cut(df['1'], [0, 50, 100,200])

         0    1        file         bin
0  person1   24     age.csv     (0, 50]
1  person2   17     age.csv     (0, 50]
2  person3   98     age.csv   (50, 100]
3  person4    6     age.csv     (0, 50]
4  person2  166  Height.csv  (100, 200]
5  person3  125  Height.csv  (100, 200]
6  person5  172  Height.csv  (100, 200]

如果您想自己命名垃圾箱,可以使用labels=参数,如下所示:

df['bin'] = pd.cut(df['1'], [0, 50, 100,200], labels=['0-50', '50-100', '100-200'])

         0    1        file      bin
0  person1   24     age.csv     0-50
1  person2   17     age.csv     0-50
2  person3   98     age.csv   50-100
3  person4    6     age.csv     0-50
4  person2  166  Height.csv  100-200
5  person3  125  Height.csv  100-200
6  person5  172  Height.csv  100-200