pandas 将小数格式化为列中的百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45989858/
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
Format decimals as percentages in a column
提问by Johnny Metz
Let's say I have the following pandas DataFrame:
假设我有以下 Pandas DataFrame:
df = pd.DataFrame({'name': ['Johnny', 'Brad'], 'rating': [1.0, 0.9]})
I want to convert the rating
column from a decimal to a percentage as a string (e.g. 1.0
to '100%'
). The following works okay:
我想将rating
列从小数转换为字符串形式的百分比(例如1.0
to '100%'
)。以下工作正常:
def decimal_to_percent_string(row):
return '{}%'.format(row['rating'] * 100)
df['rating'] = df.apply(func=decimal_to_percent_string, axis=1)
This seems very inefficient to me as it applies the function to the entire DataFrame which isn't ideal because my DataFrame is very large. Is there a better way to do this?
这对我来说似乎非常低效,因为它将函数应用于整个 DataFrame 这并不理想,因为我的 DataFrame 非常大。有一个更好的方法吗?
回答by cs95
Use pandas' broadcasting operations:
使用 pandas 的广播操作:
df.rating = (df.rating * 100).astype(str) + '%'
df
name rating
0 Johnny 100.0%
1 Brad 90.0%
Alternatively, using df.mul
and df.add
:
或者,使用df.mul
和df.add
:
df.rating = df.rating.mul(100).astype(str).add('%')
df
name rating
0 Johnny 100.0%
1 Brad 90.0%
回答by Scott Boston
df['rating'] = df['rating'].mul(100).astype(int).astype(str).add('%')
print(df)
Output:
输出:
name rating
0 Johnny 100%
1 Brad 90%
回答by whateveros
Try this:
尝试这个:
df['rating'] = pd.Series(["{0:.2f}%".format(val*100) for val in df['rating']], index = df.index)
print(df)
The output is:
输出是:
name rating
0 Johnny 100.00%
1 Brad 90.00%