我正在处理一份资产负债表,我用以下方法将其解析为熊猫:
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标识行,去掉$符号和逗号,转换成float。在
^{pr2}$这将产生以下输出:
<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函数时,我得到了一个“unhashable type”错误。在
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}}
如果我没听错,您正在寻找
apply
方法:这会创建一个新对象。要存储新对象而不是旧对象,请执行以下操作:
^{pr2}$您只需打印这些文件,而不是将它们^{} -发送到数据框中,以下是一种方法:
创建一个函数来执行条带化(如果是unicode),或者如果已经是一个数字,则保留它:
例如:
^{pr2}$更新:
对于您给出的
thread
,我很想给出一个稍微懒一点的no_comma_or_dollar
和{a2}:相关问题 更多 >
编程相关推荐