![](/img/trans.png)
[英]How do I split a string into several columns in a dataframe with pandas Python?
[英]How do I edit the string format of several Pandas DataFrame float columns?
我有一个pd.DataFrame
的浮点数:
import numpy as np
import pandas as pd
pd.DataFrame(np.random.rand(5, 5))
0 1 2 3 4
0 0.795329 0.125540 0.035918 0.645191 0.819097
1 0.755365 0.333681 0.466814 0.892638 0.610947
2 0.545204 0.313946 0.538049 0.237857 0.365573
3 0.026813 0.867013 0.843798 0.923359 0.464778
4 0.514968 0.201144 0.853341 0.951981 0.214948
我正在尝试将它们全部格式化为百分比:
0 1 2 3 4
0 "25.60%" "11.55%" "98.62%" "73.16%" "38.85%"
1 "26.01%" "28.57%" "65.21%" "32.55%" "93.45%"
2 "19.99%" "41.97%" "57.21%" "61.26%" "83.34%"
3 "41.54%" "71.02%" "52.93%" "42.78%" "49.77%"
4 "33.77%" "70.48%" "36.64%" "97.42%" "83.19%"
或者
0 1 2 3 4
0 25.60% 11.55% 98.62% 73.16% 38.85%
1 26.01% 8.57% 65.21% 32.55% 93.45%
2 19.99% 41.97% 57.21% 61.26% 83.34%
3 41.54% 1.02% 52.93% 42.78% 49.77%
4 33.77% 70.48% 36.64% 97.42% 83.19%
存在许多解决方案,但对于单个列,例如此处。 我正在尝试编辑这些值,所以我对更改浮动显示格式不感兴趣。
我该如何继续?
尝试这个:
df = df.applymap('{:,.2%}'.format)
或np.vectorize
:
df[:] = np.vectorize('{:,.2%}'.format)(df)
如果要将数字数据显示为百分比,同时保留基础数据数字而不是字符串,则可以使用数据框样式: https : //stackoverflow.com/a/55624414
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.