我有一列值爲'10百萬'和'50億',並且想要一個簡單的方法將其轉換爲數值來做一些更深入的分析。 我試圖將數百萬和十億轉換爲Python列中的一個數字或整數
powers = {'billion': 10 ** 9, 'million': 10 ** 6}
def f(s):
try:
power = s[-1]
return float(s[:-1]) * powers[power]
except TypeError:
return s
df_2.applymap(f)
更新:我的大熊貓柱由0(這是NaN的),幷包括百萬千萬的其他值。 我希望這比以前更清晰 我使用了下面@MobiusKlein推薦的方法。 所以這裏是有用的堆棧跟蹤錯誤。
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-1db4b2353170> in <module>()
10 return float(quantity) * powers[magnitude]
11
---> 12 df_2.applymap(f)
13
/home/peadarcoyle/.virtualenvs/Ipython/local/lib/python2.7/site-packages/pandas/core/frame.pyc in applymap(self, func)
3725 x = lib.map_infer(_values_from_object(x), f)
3726 return lib.map_infer(_values_from_object(x), func)
-> 3727 return self.apply(infer)
3728
3729 #----------------------------------------------------------------------
/home/peadarcoyle/.virtualenvs/Ipython/local/lib/python2.7/site-packages/pandas/core/frame.pyc in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
3556 if reduce is None:
3557 reduce = True
-> 3558 return self._apply_standard(f, axis, reduce=reduce)
3559 else:
3560 return self._apply_broadcast(f, axis)
/home/peadarcoyle/.virtualenvs/Ipython/local/lib/python2.7/site-packages/pandas/core/frame.pyc in _apply_standard(self, func, axis, ignore_failures, reduce)
3646 try:
3647 for i, v in enumerate(series_gen):
-> 3648 results[i] = func(v)
3649 keys.append(v.name)
3650 except Exception as e:
/home/peadarcoyle/.virtualenvs/Ipython/local/lib/python2.7/site-packages/pandas/core/frame.pyc in infer(x)
3724 f = com.i8_boxer(x)
3725 x = lib.map_infer(_values_from_object(x), f)
-> 3726 return lib.map_infer(_values_from_object(x), func)
3727 return self.apply(infer)
3728
/home/peadarcoyle/.virtualenvs/Ipython/local/lib/python2.7/site-packages/pandas/lib.so in pandas.lib.map_infer (pandas/lib.c:56671)()
<ipython-input-12-1db4b2353170> in f(num_str)
4
5 def f(num_str):
----> 6 match = re.search(r"([0-9\.]+)\s?(million|billion)", num_str)
7 if match is not None:
8 quantity = match.group(0)
/home/peadarcoyle/.virtualenvs/Ipython/lib/python2.7/re.pyc in search(pattern, string, flags)
140 """Scan through string looking for a match to the pattern, returning
141 a match object, or None if no match was found."""
--> 142 return _compile(pattern, flags).search(string)
143
144 def sub(pattern, repl, string, count=0, flags=0):
TypeError: ('expected string or buffer', u'occurred at index Intended_Investment')
你可以縮進你的代碼嗎請 – 2014-11-06 16:26:01
這樣的事情可能有助於可能http://code.activestate.com/recipes/550818-words-to-numbers-english/ ...你應該發佈你的錯誤,如果你想幫助解決您的特定問題 – 2014-11-06 16:26:14
您沒有收到「堆棧跟蹤錯誤」。您收到一條錯誤消息,其中包含一個非常有用的堆棧跟蹤,告訴您如何找到問題。 – khelwood 2014-11-06 16:29:07