【问题标题】:How to edit source csv file data using pandas如何使用 pandas 编辑源 csv 文件数据
【发布时间】:2016-02-24 09:43:39
【问题描述】:

我有一个包含大量数据的csv文件,但是csv文件中包含的数据没有被清理。csv数据的示例如下

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

应用分组后,我没有得到正确的结果。

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 重复两次。这是因为源文件数据,在源文件中国家字段包含“X”和“X”。这就是它显示 X twise 的原因。我如何使用 pandas 忽略这个问题

【问题讨论】:

  • df['country'] = df['country'].str.strip(' ') 应该可以工作
  • @EdChum df['country'] = df['country'].str.strip(' ').count() 会起作用吗
  • 不,这个想法是你在groupby之前清理你的数据
  • @EdCum 谢谢它的工作

标签: python pandas


【解决方案1】:

您可以调用矢量化的str.strip 来修剪前导和尾随空格:

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

因此,上述内容应该可以清理您的数据,然后您可以调用 groupby 以获得所需的结果或调用 set_index 以便您可以在看起来像您真正想要的索引级别上使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2014-01-15
    相关资源
    最近更新 更多