0
Follow
0
View

PYTHON list print statment

eastnet1 注册会员
2023-01-25 03:40

One approach would be to generate a list of results containing a dictionary with the various values which you are interested in. You could achieve this with something like:

numerical = [var for var in train_1.columns if train_1[var].dtype=='float64']
results = [{'variance': (variance(train_1[var]),
            'mean': statistics.mean(train_1[var])) } for var in numerical]

for result in results:
    print(f'mean:     {result["mean"]}')
    print(f'variance: {result["variance"]}')

Note you could also do this in the initial list comprehension, but the example minimises changes.

d12208 注册会员
2023-01-25 03:40

You have all what you need. I have just only slightly changed the f-string for printing and added a list collecting the results:

import pandas as pd
import statistics
train_1 = pd.DataFrame({'Age':[30.0, 40.0, 20.0, 15.0], 'RestingBP': [60.0, 70.0, 50.0, 80.0]})
numerical = [var for var in train_1.columns if train_1[var].dtype=='float64']
lst_results = []
for var in numerical: 
    variance =  statistics.variance(train_1[var])
    mean     =  statistics.mean(train_1[var])
    lst_results.append( (var, variance, mean ) )
    print(f"variance of {var} is: {variance} and mean of {var} is: {mean}")
print(f'{lst_results=}')

gives:

variance of Age is: 122.91666666666667 and mean of Age is: 26.25
variance of RestingBP is: 166.66666666666666 and mean of RestingBP is: 65.0
lst_results=[('Age', 122.91666666666667, 26.25), ('RestingBP', 166.66666666666666, 65.0)]

And if you want a nice dictionary for storing the results along with a nice print here a debugged and improved version from the another answer:

results = [{var: {'variance': statistics.variance(train_1[var]),
                      'mean': statistics.mean(train_1[var]) }}  
    for var in train_1.columns if train_1[var].dtype=='float64']
for result in results:
    for column, calc in result.items(): 
        print(column)
        print(f'    mean:     {calc["mean"]}')
        print(f'    variance: {calc["variance"]}')
print(f'{results=}')

giving:

Age
    mean:     26.25
    variance: 122.91666666666667
RestingBP
    mean:     65.0
    variance: 166.66666666666666
results=[{'Age': {'variance': 122.91666666666667, 'mean': 26.25}}, {'RestingBP': {'variance': 166.66666666666666, 'mean': 65.0}}]

About the Author

Question Info

Publish Time
2023-01-25 03:39
Update Time
2023-01-25 03:39

Related Question

Python类方法的使用疑惑

想知道python学好基础后,往哪个方向走?

spyder的lsp python无法运行如何解决?

为什么用ecdsa Python库创建的签名对coincurve无效?

如何将python二进制STR文字转换为实际字节

python torch

我如何在一个while循环中使用多个条件?(Python)(复制)

每次循环python时保存csv文件

Python字符串中字符的删除

python文字版大富翁怎么写?