添加前缀个

问题描述:

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

注:
这很可能会在不久的将来改变,因为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