我正在使用 pandas
,并且我执行了一些计算和转换,最终我得到了两个看起来或多或少的数据帧:
ID 'abc' 'def'
Total 4 5
Slow 0 0
Normal 1 2
Fast 3 3
ID 'abc' 'def'
Total 3 4
Slow 0 0
Normal 0 1
Fast 3 3
现在,考虑到这两个数据帧,我想生成第三个数据框架,以某种方式返回第一个数据框架中第二个数据框架的成就。这样我希望结果是这样的:
ID 'abc' 'dfe'
Total 75.0% 80.0%
Slow None None
Normal 0.0% 50.0%
Fast 100.0% 100.0%
如果第一个数据框架中有0,则在结果数据框架中,我们将该单元格设置为None
或其他内容。整个想法是,最后我将将结果写入Excel文件,因此我希望在Excel中具有None
的单元格。有什么想法在Python中使用pandas
?
您可以简单地将df2
除以df1
在感兴趣的列上:
df2.loc[:,"'abc'":] = df2.loc[:,"'abc'":].div(df1.loc[:,"'abc'":]).mul(100)
ID 'abc' 'dfe'
0 Total 75.0 80.0
1 Slow NaN NaN
2 Normal 0.0 50.0
3 Fast 100.0 100.0
更新
为了按照指定的格式,您可以执行:
df2.loc[:,"'abc'":] = df2.where(df2.loc[:,"'abc'":].isna(),
df2.round(2).astype(str).add('%'))
ID 'abc' 'dfe'
0 Total 75.0% 80.0%
1 Slow NaN NaN
2 Normal 0.0% 50.0%
3 Fast 100.0% 100.0%
鉴于没有十进制位置,除了 .0
, round(2)
对显示的浮子没有影响,但是,一旦有分裂后有一些浮子带有更多小数的浮子,您就会看到所有浮子的2
小数位置。
pandas提供了一些直接指定excel文件中样式的可能性。它是有限的,但幸运的是,您确实包括一个数字选项。
import pandas as pd
# Initialize example dataframes
df1 = pd.DataFrame(
data=[[4, 5], [0, 0], [1, 2], [3, 3], [3, 3]],
index=['Total', 'Slow', 'Normal', 'Fast', 'Fast'],
columns=['abc', 'def'],
)
df2 = pd.DataFrame(
data=[[3, 4], [0, 0], [0, 1], [3, 3], [3, 3]],
index=['Total', 'Slow', 'Normal', 'Fast', 'Fast'],
columns=['abc', 'def'],
)
result_df = df2 / df1
# Change rows index into data column (to avoid any chance of having non-unique row index values,
# since the pandas styler can only handle unique row index)
result_df = result_df.reset_index()
# Write excel output file with number format styling applied
result_df.style.applymap(lambda _: 'number-format: 0.00%').to_excel('result.xlsx', engine='openpyxl', index=False)