pandas 向 Python 中的数据框列添加百分号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35661968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:46:45  来源:igfitidea点击:

Add a percent sign to a dataframe column in Python

pythonstringpandasdataframe

提问by Kevin

I've been attempting to add a percent sign to a column in my dataframe but to no avail. Would anyone have any idea?

我一直在尝试向数据框中的列添加百分号,但无济于事。有人会有什么想法吗?

import pandas as pd

names = ('jimmy', 'red', 'julie', 'brad', 'oranges')
score = (82, 38 , 55, 19, 33)

df = pd.DataFrame({'Name': names, 'Grade': score})

df
Out[20]: 
   Grade     Name
0     82    jimmy
1     38      red
2     55    julie
3     19     brad
4     33  oranges

I've made numerous attempts but nothing seems to work out. Here is one failed attempt:

我已经进行了多次尝试,但似乎没有任何效果。这是一次失败的尝试:

df['Percent'] = str(df['Grade']) + '%'
df['Percent']
Out[22]: 
0    0    82\n1    38\n2    55\n3    19\n4    33\nN...
1    0    82\n1    38\n2    55\n3    19\n4    33\nN...
2    0    82\n1    38\n2    55\n3    19\n4    33\nN...
3    0    82\n1    38\n2    55\n3    19\n4    33\nN...
4    0    82\n1    38\n2    55\n3    19\n4    33\nN...
Name: Percent, dtype: object

回答by EdChum

Cast the dtypeto strusing astype:

投射dtypestr使用astype

In [11]:
df['Percent'] = df['Grade'].astype(str) + '%'
df

Out[11]:
   Grade     Name Percent
0     82    jimmy     82%
1     38      red     38%
2     55    julie     55%
3     19     brad     19%
4     33  oranges     33%

What you tried just converted the column to a stringified version of a Series:

您尝试的只是将列转换为 a 的字符串化版本Series

In [12]:
str(df['Grade'])

Out[12]:
'0    82\n1    38\n2    55\n3    19\n4    33\nName: Grade, dtype: int32'

回答by B. M.

You can do it like that too :

你也可以这样做:

df['Percent'] = df['Grade'].apply( lambda x : str(x) + '%')