Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

string - Add a percent sign to a dataframe column in Python

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
1    38
2    55
3    19
4    33
N...
1    0    82
1    38
2    55
3    19
4    33
N...
2    0    82
1    38
2    55
3    19
4    33
N...
3    0    82
1    38
2    55
3    19
4    33
N...
4    0    82
1    38
2    55
3    19
4    33
N...
Name: Percent, dtype: object
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Cast the dtype to str using 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:

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

Out[12]:
'0    82
1    38
2    55
3    19
4    33
Name: Grade, dtype: int32'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...