Skip to main content
 首页 » 编程设计

python之基于条件的格式编号

2024年11月01日15zhenyulu

我是 python 的新手,正在为一个简单的格式问题而苦苦挣扎。我有一个包含两列的表格 - 指标和值(value)。我希望根据指标名称(在指标列中)格式化值。似乎无法让它工作。我希望数字显示为#、###,名称为“Pct ...”的指标显示为#.#%。代码运行正常,但未进行任何更改。此外,某些值可能是空值。不确定如何处理。

# format numbers and percentages 
pct_options = ['Pct Conversion', 'Pct Gross Churn', 'Pct Net Churn'] 
for x in pct_options: 
  if x in df['metrics']:  
    df.value.mul(100).astype('float64').astype(str).add('%') 
  else: 
    df.value.astype('float64') 

请您参考如下方法:

IIUC,你可以用 isin 来做, 尝试

#first convert your column to float if necessary note you need to reassign the column 
df.value = df.value.astype('float64') 
#then change only the rows with the right metrics with a mask created with isin 
mask_pct = df.metrics.isin(pct_options) 
df.loc[mask_pct, 'value'] = df.loc[mask_pct, 'value'].mul(100).astype(str).add('%') 

在这里编辑可能是你想要的:

#example df 
df = pd.DataFrame({'metrics': ['val', 'Pct Conversion', 'Pct Gross Churn', 'ind', 'Pct Net Churn'], 'value': [12345.5432, 0.23245436, 0.4, 13, 0.000004]}) 
print (df) 
           metrics         value 
0              val  12345.543200 
1   Pct Conversion      0.232454 
2  Pct Gross Churn      0.400000 
3              ind     13.000000 
4    Pct Net Churn      0.000004 
#change the formatting with np.where 
pct_options = ['Pct Conversion', 'Pct Gross Churn', 'Pct Net Churn'] 
df.value = np.where(df.metrics.isin(pct_options), df.value.mul(100).map('{:.2f}%'.format), df.value.map('{:,.2f}'.format)) 
           metrics      value 
0              val  12,345.54 
1   Pct Conversion     23.25% 
2  Pct Gross Churn     40.00% 
3              ind      13.00 
4    Pct Net Churn      0.00%