我使用 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/