从字符串中分隔数字并使用pandas添加数字

时间:2017-10-31 06:23:08

标签: python python-2.7 pandas

这是我的代码!!

<input type="checkbox" class="category_filter" value="all" checked="checked">&nbsp;All</input>
<br />

<input type="checkbox" class="category_filter" value="accessory">&nbsp;Accessory
<br />

<input type="checkbox" class="category_filter" value="hardware">&nbsp;Hardware
<br />

<input type="checkbox" class="category_filter" value="mobile">&nbsp;Mobile App
<br />

<input type="checkbox" class="category_filter" value="software">&nbsp;Software
<br />

<div class="wrapper">
  <div class="products" data-category="accessory">
    <h3>Accessory</h3>
    <ul>
      <li>item 1</li>
      <li>item 2</li>
      <li>item 3</li>
    </ul>
  </div>
  <div class="products" data-category="hardware">
    <h3>Hardware</h3>
    <ul>
      <li>item 4</li>
      <li>item 5</li>
      <li>item 6</li>
    </ul>
  </div>
  <div class="products" data-category="mobile">
    <h3>Mobile App</h3>
    <p> no results </p>
  </div>
  <div class="products" data-category="software">
    <h3>Software</h3>
    <ul>
      <li>item 7</li>
      <li>item 8</li>
      <li>item 9</li>
    </ul>
  </div>
</div>

也完成了数据清理。

$(".category_filter").change(function(e) {
  var $this = $(this);
  var inputValue = $this.val();
  // hide the products again
  $(".products").hide();
  // check if the input box is checked so we don't display a collection that is being unchecked
  if ($this.prop("checked")) {    
    console.log(inputValue);
    if ((inputValue = "all")) {
      $(".products").show();
    } else {
      // show the product collection we need
      $('.products[data-category="' + inputValue + '"]').show();
    }
  }
});

这给了我这样的输出

import pandas as pd
df2 = pd.DataFrame({'A': ['1,008$','4,000$','6,000$','10,00$','8,00$','45 €','45 €']})

但我的目标是将不同货币的数量加在一起,即输出应该是这样的

    result2 = df2['A'].str.replace(',','.')
    result2 = result2.str.replace('$','')
    result2 = result2.str.replace('€','')
    print (result2)

我不擅长python,请帮助我!

1 个答案:

答案 0 :(得分:2)

选项1

df2.A.str.replace(',', '.').str.extract(
    '^(?P<Value>.*)(?P<Currency>\D)$', expand=True
).apply(pd.to_numeric, errors='ignore').groupby('Currency').Value.sum()

Currency
$    29.008
€    90.000
Name: Value, dtype: float64

选项2

v = pd.to_numeric(df2.A.str[:-1].str.replace(',', '.'))
c = df2.A.str[-1]

v.groupby(c).sum()

A
$    29.008
€    90.000
Name: A, dtype: float64

选项3

d = {'$': 'dollar', '€': 'euro'}

v = pd.to_numeric(df2.A.str[:-1].str.replace(',', '.'))
c = df2.A.str[-1].map(d)

v.groupby(c).sum()

A
dollar    29.008
euro      90.000
Name: A, dtype: float64