Python Pandas : get average number of decimal

标签 python pandas dataframe decimal

我使用 panda 生成了一个包含多行和多列的数据框。

我现在正在尝试确定每列的平均小数位数。 例如:

 A     B      C 
 10.1 22.541 21.44 
 10.2 23.548 19.4
 11.2 26.547 15.45

程序将为 A 返回 1,为 B 返回 3,为 C 返回 2

考虑到我正在处理的数据帧大约有 16000 行,您是否有一种有效的方法来做到这一点?

谢谢

最佳答案

更新了代码

好的,就到这里了。可能有点复杂;)

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [10.1, 10.2, 11.2] ,'B': [22.541, 23.548, 26.547],'C':[21.44,19.4,15.45]})
df

Out[1]:
       A    B       C
0   10.1    22.541  21.44
1   10.2    23.548  19.4
2   11.2    26.547  15.45


[sum((df[col].astype(str).str.split('.', expand=True)[1]).apply(lambda x: len(str(x))))/len((df[col].astype(str).str.split('.', expand=True)[1]).apply(lambda x: len(str(x)))) for col in df.columns]

Out[2]:
[1.0, 3.0, 1.6666666666666667]

逐步实现

df1 = pd.DataFrame([(df[col].astype(str).str.split('.', expand=True)[1]).apply(lambda x: len(str(x))).values for col in df.columns]).T
df1

Out[3]:
    0   1   2
0   1   3   2
1   1   3   1
2   1   3   2

df1.mean()

Out[4]:
0    1.000000
1    3.000000
2    1.666667
dtype: float64

关于Python Pandas : get average number of decimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58808025/

相关文章:

python - 在定义的轴上使用最大值索引

python - 使用 sudo 在 Python 3.6 中导入错误?

python - QPlainTextEdit 是 RightToLeft 但显示 LeftToRight

python - 基于类别列表虚拟化变量

python - 为 Django View 实现 HTTP Digest Auth

python - Plotly 中的水平条形图使用带有 2 条迹线的袖扣

Python用线性插值正则化不规则时间序列

python-3.x - Pandas pd.cut() - 合并日期时间列/系列

python - 基于值超过阈值的 Pandas 重采样

r - 具有混合数据类型的数据框