2

我正在处理一个已解析为 pandas 的资产负债表:

    table = xls_file.parse('Consolidated_Balance_Sheet')
    table.ix[:, 1]

    0         None
    1         None
    2      $ 3,029
    3         1989
    5         None
    6     $ 34,479

我正在尝试使用 unicode 识别行并去掉 $ 符号和逗号,转换为浮点数。

    for row in table.ix[:, 1]:
        if isinstance(row, unicode):
            print type(row), row
            num = float(row.lstrip('$').replace(',',''))
            print num
            row = num
            print type(row), row

这会产生以下输出:

    <type 'unicode'> $ 3,029
    3029.0
    <type 'float'> 3029.0
    <type 'unicode'> $ 34,479
    34479.0
    <type 'float'> 34479.0

但是,当我检查表格时,该值没有变化

    table.ix[2, 1]
    u'$ 3,029'

如何正确地将值更改为浮点数?

编辑:感谢您的两个回复,我可以毫无问题地重现那些回复。但是,当我对我的案例使用 apply 函数时,我得到一个“不可散列类型”错误。

In [167]: thead = table.head()
In [168]: thead

Out[168]:
         Consolidated Balance Sheet (USD $)  Sep. 30, 2012  Dec. 31, 2011
    0    In Millions, unless otherwise specified     None    None
    1    Current assets                              None    None
    2    Cash and cash equivalents                   $ 3,029 $ 2,219
    3    Marketable securities - current             1989    1461
    4    Accounts receivable - net                   4409    3867

In [170]: def no_comma_or_dollar(num):
              if isinstance(num, unicode):
                  return float(num.lstrip('$').replace(',',''))
              else:
                  return num

          thead[:, 1] = thead[:, 1].apply(no_comma_or_dollar)

产生以下内容:

 TypeError: unhashable type

我不明白为什么,因为我没有改变键,只是改变了值。还有其他方法可以更改数据框中的值吗?

编辑2

In [171]: thead.to_dict()
Out[171]: {u'Consolidated Balance Sheet (USD $)': {0: u'In Millions, unless otherwise specified',
  1: u'Current assets',
  2: u'Cash and cash equivalents',
  3: u'Marketable securities - current',
  4: u'Accounts receivable - net'},
 u'Dec. 31, 2011': {0: None, 1: None, 2: u'$ 2,219', 3: 1461.0, 4: 3867.0},
 u'Sep. 30, 2012': {0: None, 1: None, 2: u'$ 3,029', 3: 1989.0, 4: 4409.0}}
4

2 回答 2

3

您只是打印这些而不是apply将它们添加到 DataFrame,这是一种方法:

创建一个函数来进行条带化(如果是 unicode),或者如果已经是一个数字则保留它:

def no_comma_or_dollar(num):
    if isinstance(num, unicode):
        return float(num.lstrip('$').replace(',',''))
    else:
        return num

table[col_name] = table[col_name].apply(no_comma_or_dollar)

例如:

df = pd.DataFrame([[u'$1,000'], [200.]])

In [3]: df[0].apply(no_comma_or_dollar)
Out[3]: 
0    1000
1     200
Name: 0

更新:

有了thread你给出的,我很想给出一个稍微懒一点的no_comma_or_dollarand版本applymap

def no_comma_or_dollar2(num):
    try:
        return float(num.lstrip('$').replace(',',''))
    except: # if you can't strip/replace/convert just leave it
        return num

In [5]: thread.applymap(no_comma_or_dollar2)
Out[5]: 
        Consolidated Balance Sheet (USD $)  Dec. 31, 2011  Sep. 30, 2012
0  In Millions, unless otherwise specified            NaN            NaN
1                           Current assets            NaN            NaN
2                Cash and cash equivalents           2219           3029
3          Marketable securities - current           1461           1989
4                Accounts receivable - net           3867           4409
于 2013-01-19T17:46:39.677 回答
3

如果我理解正确,您正在寻找apply方法:

In [33]: import pandas as pd

In [34]: table = pd.Series([None, u'$ 3,12', u'$ 4,5'])

In [35]: table
Out[35]: 
0      None
1    $ 3,12
2     $ 4,5

In [36]: def f(cell):
   ....:     if isinstance(cell, unicode):
   ....:         return float(cell.lstrip('$').replace(',',''))
   ....:     else:
   ....:         return cell
   ....:     

In [37]: table.apply(f)
Out[37]: 
0    NaN
1    312
2     45

这确实创建了一个新对象。为了存储新对象而不是旧对象,请执行以下操作:

In [42]: table = table.apply(f)

In [43]: table
Out[43]: 
0    NaN
1    312
2     45
于 2013-01-19T17:46:54.587 回答