假设我有以下 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%