python - Pandas :将特定行更改为百分比

标签 python pandas dataframe

我在 Pandas 数据框中有一行包含我的商品的销售率。

看看我的数据:

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

我可以通过执行以下操作轻松计算销售额百分比:

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

现在我要做的是将“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"]])


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

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

最佳答案

你可以使用.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)

产量

                    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%

注意 Python str.format 方法有一个 built-in % format它将数字乘以 100 并以固定 ('f') 格式显示,后跟百分号。


请务必注意,Pandas DataFrame 列必须具有单一数据类型。将一个值更改为字符串会强制更改整列 它的 dtype 为通用 object dtype。因此 int64int32Total ListingsTotal Sales 行被重铸为纯 Python int。这个 防止 Pandas 利用基于 NumPy 的快速数值运算 它只适用于原生 NumPy dtypes(如 int64float64 - 不是 对象)。

因此,虽然上面的代码达到了预期的效果,但不建议使用 如果要在 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)

产量

   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%

原因

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

将值向左移动一列是因为新 Series 的索引从 0 而不是 1 开始。Pandas aligns 右侧 Series 的索引与 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)

关于python - Pandas :将特定行更改为百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38107304/

相关文章:

python - 在 Python 中添加字母数字中的正则表达式

python - Django-tables2 - 动态地向表中添加列 - 不向 html 中的表标签添加属性

python - SQLite 查询性能、Transpose、Melt 和 Pandas

python - 高效简洁的GroupBy扰列透传

python - 在 pandas DataFrame 多索引函数之外解压列表

python - 为非卡住集设置成员资格

python - 如何在 Dataframe 的列的单元格中取消嵌套 2x2 数组?

python pandas read_excel 在 describe() 上返回 UnicodeDecodeError

r - 根据来自不同数据帧的 2 个键定义数据帧中列的值

python - pandas.DataFrame 中重复列的有趣结果