添加前缀失败百分比

Add prefix failed with percentage

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 函数与 % 一起使用?

还是只是bug?

通知:

可能的解决方案如下:

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

但我对函数 add_prefix 感兴趣。

注意:
这可能会在不久的将来发生变化,因为 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'