添加前缀失败,出现百分比 [英] Add prefix failed with percentage

查看:89
本文介绍了添加前缀失败,出现百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

df = pd.DataFrame({'a':[1,4], 'b':[7,8]})
print (df)
   a  b
0  1  7
1  4  8

我尝试将%添加到列名,所以使用

I try add % to columns names, so use DataFrame.add_prefix

print (df.add_prefix('%'))

TypeError:在字符串格式化期间并非所有参数都已转换

TypeError: not all arguments converted during string formatting

有什么问题吗?

如何将add_prefix函数与%一起使用?

How is possible use add_prefix function with % ?

还是只有错误?

通知:

可能的解决方案是:

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

但是我对函数add_prefix感兴趣.

推荐答案

注意:
这可能会在不久的将来改变,因为pandas在这种情况下将使用新的样式字符串格式.发生这种情况时:

NOTE:
This is likely to change in the near future as pandas will use new style string formatting in this case. When that happens:

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

'%hello'

添加带有单个%的前缀就可以了.

adding a prefix with a single % will work just fine.

请参见github

答案
两个百分号!使用旧样式的字符串格式时,一个会跳过另一个.

Answer
Two percent signs! One escapes the other when using the old style of string formatting.

df.add_prefix('%%')

   %a  %b
0   1   7
1   4   8


线索来自:


The clue came from:

   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

因此,我查找了如何以旧的字符串格式样式转义'%'并找到了 此答案

So I looked up how to escape the '%' in the old style of string formatting and found this answer

是什么原因导致的

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

'%hello'

这篇关于添加前缀失败,出现百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆