熊猫:将特定行更改为百分比

Kev*_*vin 5 python dataframe pandas

我在Pandas Data框架中有一行,其中包含我的商品的销售率.

看看我的数据:

block_combine
Out[78]: 
END_MONTH         1    2    3   4    5
Total Listings  168  219  185  89  112
Total Sales      85   85   84  41   46
Run Code Online (Sandbox Code Playgroud)

通过执行以下操作,我可以轻松计算销售额%:

block_combine.loc["Total Sales Rate"] = block_combine.ix[1,:] / block_combine.ix[0,:]
block_combine

Out[79]: 
END_MONTH                  1           2           3          4           5
Total Listings    168.000000  219.000000  185.000000  89.000000  112.000000
Total Sales        85.000000   85.000000   84.000000  41.000000   46.000000
Total Sales Rate    0.505952    0.388128    0.454054   0.460674    0.410714
Run Code Online (Sandbox Code Playgroud)

现在我要做的是将"总销售率"行更改为整数百分比.如果它是一个列,我能够这样做但是当我使用行时遇到问题.

这是我尝试的:

block_combine.loc["Total Sales Rate"] = pd.Series(["{0:.0f}%".format(val * 100) for val in block_combine.loc["Total Sales Rate"]])


block_combine

Out[81]: In [82]: 
END_MONTH           1    2    3    4      5
Total Listings    168  219  185   89  112.0
Total Sales        85   85   84   41   46.0
Total Sales Rate  39%  45%  46%  41%    NaN
Run Code Online (Sandbox Code Playgroud)

计算关闭/向左移动.第1个月的销售率实际上是第2个月的销售率(39%)!

unu*_*tbu 7

你可以使用.apply('{:.0%}'.format):

import pandas as pd

df = pd.DataFrame([(168,219,185,89,112), (85,85,84,41,46)], 
                  index=['Total Listings', 'Total Sales'], columns=list(range(1,6)))
df.loc['Total Sales Rate'] = ((df.loc['Total Sales']/df.loc['Total Listings'])
                              .apply('{:.0%}'.format))

print(df)
Run Code Online (Sandbox Code Playgroud)

产量

                    1    2    3    4    5
Total Listings    168  219  185   89  112
Total Sales        85   85   84   41   46
Total Sales Rate  51%  39%  45%  46%  41%
Run Code Online (Sandbox Code Playgroud)

请注意,Python str.format方法具有内置%格式,该数字将数字乘以100并以固定('f')格式显示,后跟百分号.


请务必注意,Pandas DataFrame列必须具有单个dtype.将一个值更改为字符串会强制整个列将其dtype更改为泛型objectdtype.因此,和行中的int64s或int32s 将重命名为普通Python .这可以防止Pandas利用基于NumPy的快速数值运算,这些运算仅适用于原生NumPy dtypes(如或不是 ).Total ListingsTotal Salesintsint64float64object

因此,虽然上面的代码实现了所需的外观,但如果要对DataFrame进行进一步的计算,则不建议使用它.相反,如果您需要进行演示,最后只转换为字符串.

或者,或者,转置您的DataFrame,使Total Sales Rate字符串在一列而不是一行:

import pandas as pd

df = pd.DataFrame([(168,219,185,89,112), (85,85,84,41,46)], 
                  index=['Total Listings', 'Total Sales'], columns=list(range(1,6))).T

df['Total Sales Rate'] = ((df['Total Sales']/df['Total Listings'])
                              .apply('{:.0%}'.format))

print(df)
Run Code Online (Sandbox Code Playgroud)

产量

   Total Listings  Total Sales Total Sales Rate
1             168           85              51%
2             219           85              39%
3             185           84              45%
4              89           41              46%
5             112           46              41%
Run Code Online (Sandbox Code Playgroud)

之所以

block_combine.loc["Total Sales Rate"] = pd.Series(["{0:.0f}%".format(val * 100) for val in block_combine.loc["Total Sales Rate"]])
Run Code Online (Sandbox Code Playgroud)

将值向左移动一列是因为新系列的索引从0开始而不是1. Pandas 右侧系列的索引与block_combine.loc["Total Sales Rate"]分配值之前的索引对齐block_combine.loc["Total Sales Rate"].

因此,您可以使用:

block_combine.loc["Total Sales Rate"] = pd.Series(["{0:.0f}%".format(val * 100) 
    for val in block_combine.loc["Total Sales Rate"]], 
    index=block_combine.columns)
Run Code Online (Sandbox Code Playgroud)