如何从熊猫数据帧列的填充程度中获取百分比?



我想确定.csv文件中每一列的满度,请按每列的满满顺序将它们添加到列表中。饱满度应以百分比表示。

.csv文件非常大,因此确定哪些列包含少量数据以及哪些列包含最多数据会很有用。因此,具有更多数据的列对我更有用。

到目前为止,我得到了什么:

import pandas as pd
ranked_list = []
csv_filepath = r"some_path_here"
data = pd.read_csv(filepath)
for column in data:
way_to_calculate_percentage
ranked_list.append(way_to_calculate_percentage)
print(sorted(ranked_list))

我想知道是否有办法确定这个"way_to_calculate_percentage">

干杯!

DataFrame.notna检查非缺失值,并在需要时mean计数非缺失值的百分比:

data = pd.DataFrame({
'A':list('abcdef'),
'B':[4,np.nan,4,np.nan,np.nan,4],
'C':[7,8,9,4,2,3],
'D':[1,3,np.nan,7,1,0],
})
s1 = data.notna().mean()
print (s1)
A    1.000000
B    0.500000
C    1.000000
D    0.833333
dtype: float64

如果需要缺失值的百分比,请使用DataFrame.isnamean

s2 = data.isna().mean().sort_values()
print (s2)
A    0.000000
C    0.000000
D    0.166667
B    0.500000
dtype: float64

然后是可能的分析值 - 用Series.nlargestSeries.nsmallest并在必要时使用Series.sort_values

s3 = s2.nlargest(2)
print (s3)
B    0.500000
D    0.166667
dtype: float64
s4 = s2.nsmallest(2)
print (s4)
A    0.0
C    0.0
dtype: float64
s5 = s2.sort_values()
print (s5)
A    0.000000
C    0.000000
D    0.166667
B    0.500000
dtype: float64

假设您有以下数据帧:

a    b
0  NaN  NaN
1  1.0  NaN
2  2.0  NaN
3  3.0  4.0

您可以像这样计算每列的百分比:

null_percent = df.isnull().sum() / df.shape[0]

结果:

a    0.25
b    0.75
dtype: float64

这有帮助吗?

df
Out[13]: 
ColumnA ColumnB ColumnC ColumnD
0    TypeA       A       a       x
1    TypeA       B     NaN       x
2    TypeA       C       b       x
3    TypeA       D     NaN       x
4    TypeA       E     NaN       x
5    TypeB       F     NaN       x
6    TypeB       A       g       x
7    TypeC       B     NaN       x
8    TypeC       Z     NaN     NaN
9    TypeC       C     NaN     NaN
10   TypeD       A       h     NaN
df.notna().sum()/len(df)*100
Out[14]: 
ColumnA    100.000000
ColumnB    100.000000
ColumnC     36.363636
ColumnD     72.727273
dtype: float64

我的解决方案是提供使用大小的内存占用

import pandas as pd
import os
dir_path = 'M:/Desktop/Python-Test/'
test_file = os.path.join(dir_path, 'test_file.csv')
pd1 = pd.read_csv(test_file)
print(pd1.memory_usage(index=False, deep=True))

最新更新