一个数据帧的索引的最左位数字重复0-9的频率?

时间:2019-01-17 02:51:47

标签: python pandas dataframe count frequency

我想知道我们是否可以计算在某些熊猫数据帧的index的最左位重复0-9的频率:

             A          B           C
0   -56.343656        NaN -418.540483
10  -87.577880 -16.061497         NaN
20         NaN -15.337254         NaN
40  -67.462841        NaN -431.924830
50  -63.377158 -28.260790         NaN
60         NaN -22.996095         NaN
130  11.569845        NaN -307.034737
180  11.398947  -1.793530         NaN

我已经提取了那些包含前导0的列的索引:

000
010
020
040
050
060
130
180

,并尝试将提取的索引存储在csv文件中。然后我甚至尝试再次将它们放在数据框中,根据这个原理,最左边的数字可以是[0-7],第二个最左边的数字可以是[0-59],最后一个数字可以是[0-9999]并存储在csv中文件仅在代表最左边数字列的'section'列上进行进一步处理。

我的脚本如下:

import numpy as np
import pandas as pd


df = pd.read_csv('D:\SOF.TXT', header=None)
id_set = df[df.index % 4 == 0].astype('int').values
A = df[df.index % 4 == 1].values
B = df[df.index % 4 == 2].values
C = df[df.index % 4 == 3].values

data = {'A': A[:,0], 'B': B[:,0], 'C': C[:,0]}
#main_data contains all the data
main_data = pd.DataFrame(data, columns=['A','B','C'], index = id_set[:,0])  


main_data[np.isinf(main_data)] = np.nan    # convert inf to nan
main_data_nan = main_data[main_data.isnull().any(axis=1)]   # extract sub data frame
print(main_data_nan)
# to fix 3 digits of index in start
new_index = [str(x).zfill(3) for x in main_data_nan.index]
main_data_nan.index = new_index
#print all data includes nan values in .csv file
main_data_nan.to_csv('nan_data.csv', na_rep='NaN')   # export
#print just especial column that includes nan values in .csv file including id_set or indexes
main_data_nan['C'].to_csv('nan_datatemp.csv', na_rep='NaN')
#print all id_set which is index in data frame has nan values
for i in range(len(main_data_nan)):
    print (main_data_nan.index[i])


dff = pd.read_csv("D:\nan_datatemp.csv")
cycle, section, cell = [], [], []
for i in range(9999):
    for j in range(8):
        for k in range(60):
            cycle.append(i)
            section.append(j)
            cell.append(k)
dfff = {'Section':section, 'Cell':cell, 'Cycle':cycle}
dffff = pd.DataFrame(dfff, columns=['Section','Cell', 'Cycle'], index = id_set[:,0])
dffff.to_csv('exit_id_det.csv', encoding='utf-8', index=False)

我不确定here的答案是否可以通过在最左边的数字索引上应用(df==X).sum()来满足我的答案,

(df==0).sum()
(df==1).sum()
(df==2).sum()
(df==3).sum()
(df==4).sum()
(df==5).sum()
(df==6).sum()
(df==7).sum()

,甚至使用main_data_nan.isnull().sum().sum()计算它们出现频率的百分比 我的愿望结果应该是:

索引 ----> 频率 ---> 百分比
0 00 ----> 0:6倍----> 0:总计75%
0 10 ----> 1:2倍----> 1:总计25%
0 20 ----> 2:0倍----> 2:总计0%
0 40 ----> 3:0倍----> 3:总计3%
0 50 ----> 4:0倍----> 4:0%总计
0 60 ----> 5:0倍----> 5:0%总计
1 30 ----> 6:0倍----> 6:0%总计
1 80 ----> 7:0倍----> 7:0%总计

以下是我的数据集示例:dataset sample DL link

1 个答案:

答案 0 :(得分:0)

从索引中创建一个名为index的新列,然后查找压缩您的数据框,因此您只有包含空值的列观察值。然后计算每个部分的最左边数字。

import collections

df['index'] = df.index
null_data = df[df.isnull().any(axis=1)]
cycle_left = collections.Counter(null_data['index']//100%10)
cell_left = collections.Counter(null_data['index']//10000%10)
section_left = collections.Counter(null_data['index']//100000%10)

输出将是一个字典,其中的键是最左边的数字,而值是每个数字的频率。

现在,让我们假设您在索引427888, 101, 6123456上具有空值。

示例输出:

Counter({1: 1, 8: 1, 4: 1})     #cycle_left
Counter({2: 2, 0: 1})           #cell_left
Counter({0: 1, 4: 1, 1: 1})     #section_left

您还可以在最后一步中使用.value_counts()来获取包含频率的序列(索引将是最左边的数字,而值将是该数字的频率)。

df['index'] = df.index
null_data = df[df.isnull().any(axis=1)]
cycle_left = (null_data['index']//100%10).value_counts()
cell_left = (null_data['index']//10000%10).value_counts()
section_left = (null_data['index']//100000%10).value_counts()

示例输出:

#cycle_left
4    1
1    1
8    1
Name: index, dtype: int64

#cell_left
2    2
0    1
Name: index, dtype: int64

#section_left
1    1
4    1
0    1
Name: index, dtype: int64