假设我有以下 Pandas DataFrame:
df = pd.DataFrame({'name': ['Johnny', 'Brad'], 'rating': [1.0, 0.9]})
我想将
rating
列从十进制转换为字符串形式的百分比(例如 1.0
到 '100%'
)。以下工作正常:def decimal_to_percent_string(row):
return '{}%'.format(row['rating'] * 100)
df['rating'] = df.apply(func=decimal_to_percent_string, axis=1)
这对我来说似乎非常低效,因为它将函数应用于整个 DataFrame 这并不理想,因为我的 DataFrame 非常大。有一个更好的方法吗?
最佳答案
使用 pandas 的广播操作:
df.rating = (df.rating * 100).astype(str) + '%'
df
name rating
0 Johnny 100.0%
1 Brad 90.0%
或者,使用
df.mul
和 df.add
:df.rating = df.rating.mul(100).astype(str).add('%')
df
name rating
0 Johnny 100.0%
1 Brad 90.0%
关于python - 将小数格式化为列中的百分比,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45989858/