我想创建一个 24x20 矩阵(8 个部分,每个部分有 60 个单元格或 6x10),用于通过 panda 数据框在数据集中通过周期(=每个480 个值)可视化缺失数据出现的频率,并为每一列绘制它,,.'A'
'B'
'C'
到目前为止,我可以映射创建的 csv 文件并在矩阵中以正确的方式映射值,并sns.heatmap(df.isnull())
在将缺失数据(nan & inf)更改为对数据影响最小的0
东西或类似0.01234
的东西后绘制它,另一方面可以被绘制。以下是我到目前为止的脚本:
import numpy as np
import pandas as pd
import os
import seaborn as sns
import matplotlib.pyplot as plt
def mkdf(ListOf480Numbers):
normalMatrix = np.array_split(ListOf480Numbers,8)
fixMatrix = []
for i in range(8):
lines = np.array_split(normalMatrix[i],6)
newMatrix = [0,0,0,0,0,0]
for j in (1,3,5):
newMatrix[j] = lines[j]
for j in (0,2,4):
newMatrix[j] = lines[j][::-1]
fixMatrix.append(newMatrix)
return fixMatrix
def print_df(fixMatrix):
values = []
for i in range(6):
values.append([*fixMatrix[6][i], *fixMatrix[7][i]])
for i in range(6):
values.append([*fixMatrix[4][i], *fixMatrix[5][i]])
for i in range(6):
values.append([*fixMatrix[2][i], *fixMatrix[3][i]])
for i in range(6):
values.append([*fixMatrix[0][i], *fixMatrix[1][i]])
df = pd.DataFrame(values)
return (df)
dft = pd.read_csv('D:\Feryan.TXT', header=None)
id_set = dft[dft.index % 4 == 0].astype('int').values
A = dft[dft.index % 4 == 1].values
B = dft[dft.index % 4 == 2].values
C = dft[dft.index % 4 == 3].values
data = {'A': A[:,0], 'B': B[:,0], 'C': C[:,0]}
df = pd.DataFrame(data, columns=['A','B','C'], index = id_set[:,0])
nan = np.array(df.isnull())
inf = np.array(df.isnull())
df = df.replace([np.inf, -np.inf], np.nan)
df[np.isinf(df)] = np.nan # convert inf to nan
#dff = df[df.isnull().any(axis=1)] # extract sub data frame
#df = df.fillna(0)
#df = df.replace(0,np.nan)
#next iteration create all plots, change the number of cycles
cycles = int(len(df)/480)
print(cycles)
for cycle in range(3):
count = '{:04}'.format(cycle)
j = cycle * 480
new_value1 = df['A'].iloc[j:j+480]
new_value2 = df['B'].iloc[j:j+480]
new_value3 = df['C'].iloc[j:j+480]
df1 = print_df(mkdf(new_value1))
df2 = print_df(mkdf(new_value2))
df3 = print_df(mkdf(new_value3))
for i in df:
try:
os.mkdir(i)
except:
pass
df1.to_csv(f'{i}/norm{i}{count}.csv', header=None, index=None)
df2.to_csv(f'{i}/norm{i}{count}.csv', header=None, index=None)
df3.to_csv(f'{i}/norm{i}{count}.csv', header=None, index=None)
#plotting all columns ['A','B','C'] in-one-window side by side
fig, ax = plt.subplots(nrows=1, ncols=3 , figsize=(20,10))
plt.subplot(131)
ax = sns.heatmap(df1.isnull(), cbar=False)
ax.axhline(y=6, color='w',linewidth=1.5)
ax.axhline(y=12, color='w',linewidth=1.5)
ax.axhline(y=18, color='w',linewidth=1.5)
ax.axvline(x=10, color='w',linewidth=1.5)
plt.title('Missing-data frequency in A', fontsize=20 , fontweight='bold', color='black', loc='center', style='italic')
plt.axis('off')
plt.subplot(132)
ax = sns.heatmap(df2.isnull(), cbar=False)
ax.axhline(y=6, color='w',linewidth=1.5)
ax.axhline(y=12, color='w',linewidth=1.5)
ax.axhline(y=18, color='w',linewidth=1.5)
ax.axvline(x=10, color='w',linewidth=1.5)
plt.title('Missing-data frequency in B', fontsize=20 , fontweight='bold', color='black', loc='center', style='italic')
plt.axis('off')
plt.subplot(133)
ax = sns.heatmap(df3.isnull(), cbar=False)
ax.axhline(y=6, color='w',linewidth=1.5)
ax.axhline(y=12, color='w',linewidth=1.5)
ax.axhline(y=18, color='w',linewidth=1.5)
ax.axvline(x=10, color='w',linewidth=1.5)
plt.title('Missing-data frequency in C', fontsize=20 , fontweight='bold', color='black', loc='center', style='italic')
plt.axis('off')
plt.suptitle(f'Missing-data visualization', color='yellow', backgroundcolor='black', fontsize=15, fontweight='bold')
plt.subplots_adjust(top=0.92, bottom=0.02, left=0.05, right=0.96, hspace=0.2, wspace=0.2)
fig.text(0.035, 0.93, 'dataset1' , fontsize=19, fontweight='bold', rotation=42., ha='center', va='center',bbox=dict(boxstyle="round",ec=(1., 0.5, 0.5),fc=(1., 0.8, 0.8)))
#fig.tight_layout()
plt.savefig(f'{i}/result{count}.png')
#plt.show()
问题是我不知道如何正确绘制缺失数据发生的频率以了解它经常发生在哪些部分和单元格中。
注1缺失值越多,颜色越亮,循环中 100% 的缺失数据应以白色表示,纯黑色表示非缺失值。可能有一个从黑色 0% 到 100% 白色的条形图。
注2我还提供了 3 个周期的数据集示例文本文件,包括少量缺失数据,但可以手动修改和增加:数据集
预期结果应如下所示: