简体   繁体   English

Pandas - 基于列名和行值应用样式/格式

[英]Pandas - Apply Style/Formatting Based on Column Name and Value of a Row

import pandas as pd

df2 = pd.DataFrame.from_records(
{'Compared': {0: -0.090909090999999997,
  1: -0.130434783,
  2: -0.10714285699999999,
  3: -0.15966386599999999},
 'LastYR': {0: 5500.0, 1: 115.0, 2: 84.0, 3: 40520.523399999998},
 'METRIC': {0: 'Visits', 1: 'Units', 2: 'Orders', 3: 'Sales'},
 'Today': {0: 5000.0, 1: 100.0, 2: 75.0, 3: 34050.860000000001},
 'region_rollup': {0: 'America', 1: 'America', 2: 'America', 3: 'America'}}

)
df2.head()

How can I apply:我如何申请:

a) a % format to any entire column I would like a) 我想要的任何整列的 % 格式

b) A currency $ format to any row where the METRIC value is 'Sales' b) METRIC 值为“销售额”的任何行的货币 $ 格式

在此处输入图片说明

I have tried the df.style.format() function, which will let me subset columns and apply the % formatting, but I cannot determine what kind of function to write which would allow me to format a column, based on the value of another column (again, "if metric = sales then format today as currency", more or less).我已经尝试了 df.style.format() 函数,它可以让我对列进行子集化并应用 % 格式,但是我无法确定要编写哪种函数来允许我根据另一个值对列进行格式化列(同样,“如果指标 = 销售额,那么今天将格式设置为货币”,或多或少)。

Thanks!谢谢!

For first condition, if percentage of only numbers may be following would work too:对于第一个条件,如果只有数字的百分比可能会起作用:

df2['%'] = (df2['LastYR']/ df2['LastYR'].sum()) * 100

For second condition, may be you can use, for eg if METRIC is Sales then, divide some other column value, in below if Sales then dividing Today column by 100.0, else keeping same as Today column value:对于第二个条件,您可以使用,例如,如果METRICSales那么,除以其他列值,在下面如果Sales然后将Today列除以 100.0,否则与Today列值保持相同:

df2['Currency'] = df2.apply(lambda row: (row['Today'] / 100.0 if row['METRIC'] == 'Sales' else row['Today']), axis=1)

Result:结果:

   Compared      LastYR  METRIC     Today region_rollup          %   Currency
0 -0.090909   5500.0000  Visits   5000.00       America  11.899733  5000.0000
1 -0.130435    115.0000   Units    100.00       America   0.248813   100.0000
2 -0.107143     84.0000  Orders     75.00       America   0.181741    75.0000
3 -0.159664  40520.5234   Sales  34050.86       America  87.669713   340.5086

Update:更新:

Using function and using apply :使用函数和使用apply

def test_function(row):
    if row['METRIC'] == 'Sales':
        return row['Today'] / 100.0 
    else:
        return row['Today']

And using lambda and apply for each row:并使用lambdaapply每一行:

df2['Currency'] = df2.apply(lambda row: test_function(row), axis=1)

Update 2:更新 2:

def test_function(row, column):
    if row['METRIC'] == 'Sales':
        return row[column] / 100.0 
    else:
        return row[column]

df2['%'] = (df2['LastYR']/ df2['LastYR'].sum()) * 100

column_list = ['Today', 'LastYR']
for column in column_list:
    df2[column] = df2.apply(lambda row: test_function(row, column), axis=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM