2017-08-02 89 views
1
df = pd.DataFrame({'a':[1,4], 'b':[7,8]}) 
print (df) 
    a b 
0 1 7 
1 4 8 

我嘗試添加%的列名失敗,所以使用DataFrame.add_prefix添加前綴個

print (df.add_prefix('%')) 

TypeError: not all arguments converted during string formatting

可能是什麼問題?

怎麼可能使用add_prefix功能%

或者它只是錯誤?

通知

可能的解決辦法是這樣的:

df.columns = ['%' + col for col in df.columns] 
print (df) 
    %a %b 
0 1 7 
1 4 8 

,但我感興趣的有關功能add_prefix

+0

也許一個錯誤? */mapper *是'/ python2.7/site-packages/pandas/core/internals.py'中2593行(pandas 0.17.1)的'f =(str(prefix)+'%s').__ mod__' 。 – Alexander

+0

https://github.com/pandas-dev/pandas/commit/9b07ef4a5b656a1532512c270533053ee338e30d – piRSquared

回答

3

注:
這很可能會在不久的將來改變,因爲pandas將採用新樣式的字符串在這種情況下格式化。當發生這種情況:

'{}hello'.format('%') 

'%hello' 

添加前綴與單個%會工作得很好。

See github


回答
兩個百分比符號!當使用舊式的字符串格式時,其他人會轉義。

df.add_prefix('%%') 

    %a %b 
0 1 7 
1 4 8 

線索來自:

2856  def add_prefix(self, prefix): 
    2857   f = (str(prefix) + '%s').__mod__ 
-> 2858   return self.rename_axis(f, axis=0) 
    2859 
    2860  def add_suffix(self, suffix): 

所以我沒有嘗試過自己

f = ('my_prefix_' + '%s').__mod__ 
f('hello') 

'my_prefix_hello' 

然後

f = ('%' + '%s').__mod__ 
f('hello') 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-901-0c92e5498bbc> in <module>() 
     1 f = ('%' + '%s').__mod__ 
----> 2 f('hello') 

TypeError: not all arguments converted during string formatting 

於是我擡起頭來如何在舊式的字符串格式化的逃避'%',發現this answer

而導致這種

f = ('%%' + '%s').__mod__ 
f('hello') 

'%hello' 
+1

幹得好。我正在嘗試''\%''和'r'%''。仍然可能是一個bug ... – Alexander

+0

我試過同樣的東西。事實上,我有一個嘗試,出於挫折,使用'r'\\\\\\\\\\\\\\\\'%' – piRSquared