我處理我已經使用解析成大熊貓資產負債表:大熊貓據幀行更改類型
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)
產生如下:
我不能讓我的身邊,爲什麼,因爲我不改變的鑰匙,只值頭。是否有另一種方法來更改數據框中的值?
EDIT2:
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}}
你能張貼'thead.to_dict()'所以我們可以(也許)重現該問題? – unutbu
'thead.ix [:, 1] = thead.ix [:, 1] .apply(no_comma_or_dollar)'或'thead.ix [:, 1:] = thead.ix [:, 1:]。applymap(no_comma_or_dollar )'(爲兩個)應該工作。 – DSM
非常感謝,我現在要低下頭,閱讀applymap! – Ralph