2016-02-24 130 views
1

我有一个包含大量数据的csv文件,但包含在CSV文件中的数据并不CSV数据的cleaned.The例子如下如何使用熊猫

country  branch  no_of_employee  total_salary count_DOB count_email 
    x   a   30     2500000  20   25 
    x   b   20     350000   15   20 
    y   c   30     4500000  30   30 
    z   d   40     5500000  40   40 
    z   e   10     1000000  10   10 
    z   f   15     1500000  15   15 
编辑源csv文件数据

由于我没有得到正确的结果而应用该组。

df = data_df.groupby(['country', 'customer_branch']).count() 

其结果是

country branch no of employees 
x   1   30 
x   1   20 
y   1   30 
z   3   65 

国家x的形式被重复twise.This是因为源文件数据的,在源文件的国家字段包含“X”和“X”。这就是为什么它显示的X twise我。怎么可以忽略使用熊猫

这个问题
+0

'df ['country'] = df ['country']。str.strip('')'should do – EdChum

+0

@EdChum df ['country'] = df ['country']。str.strip(' ').count()会起作用 –

+0

不,这个想法是你在'groupby'之前清理你的数据 – EdChum

回答

3

可以调用矢量化str.strip修剪开头和结尾的空格:

df['country'] = df['country'].str.strip(' ') 

所以上面应该努力清理您的数据和那么你可以打电话给groupby得到想要的结果,或者​​所以你的指数水平,它看起来像你真正想要什么都可以sum

例子:

In [4]: 
df = pd.DataFrame({'country':['x', 'x ','y','z','z','z'], 'branch':list('abcdef'), 'no_of_employee':[30,20,30,40,10,15]}) 
df 

Out[4]: 
    branch country no_of_employee 
0  a  x    30 
1  b  x    20 
2  c  y    30 
3  d  z    40 
4  e  z    10 
5  f  z    15 

In [9]: 
df['country'] = df['country'].str.strip() 
df.set_index(['country', 'branch']).sum(level=0) 

Out[9]: 
     no_of_employee 
country     
x     50 
y     30 
z     65 
+0

它的作用谢谢 –