使用 pandas 从 CSV 文件中绘制列的 CDF

Plot CDF of columns from a CSV file using pandas

我想使用 pandas 绘制 CSV 文件中列的 CDF 值,如下所示:

我试过一些代码,但它们没有报告正确的情节。你能帮忙提供一个简单的方法吗?

df = pd.read_csv('pathfile.csv')
def compute_distrib(df, col):
    stats_df = df.groupby(col)[col].agg('count')\
                 .pipe(pd.DataFrame).rename(columns={col: 'frequency'})
    
    # PDF
    stats_df['pdf'] = stats_df['frequency'] / sum(stats_df['frequency'])
    
    # CDF
    stats_df['CDF'] = stats_df['pdf'].cumsum()
    
    # modifications
    stats_df = stats_df.reset_index()\
                       .rename(columns={col:"X"})
    stats_df[" "] = col
    return stats_df

cdf = []
for col in ['1','2','3','4']: 
    cdf.append(compute_distrib(df, col))
cdf = pd.concat(cdf, ignore_index=True)

import seaborn as sns

sns.lineplot(x=cdf["X"],
             y=cdf["CDF"],
             hue=cdf[" "]);

由于您的 post 上缺少可运行代码,我创建了自己的代码来绘制数据帧列的 CDF df:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from itertools import accumulate


# GENERATE EXAMPLE DATA
df = pd.DataFrame()
df['x1'] = np.random.uniform(-1,1, size=1000)
df['x2'] = df['x1'] + np.random.uniform(-1,1, size=1000)
df['x3'] = df['x2'] + np.random.uniform(-1,1, size=1000)
df['x4'] = df['x3'] + np.random.uniform(-1, 1, size=1000)

# START A PLOT
fig,ax = plt.subplots()

for col in df.columns:

  # SKIP IF IT HAS ANY INFINITE VALUES
  if not all(np.isfinite(df[col].values)):
    continue

  # USE numpy's HISTOGRAM FUNCTION TO COMPUTE BINS
  xh, xb = np.histogram(df[col], bins=60, normed=True)

  # COMPUTE THE CUMULATIVE SUM WITH accumulate
  xh = list(accumulate(xh))
  # NORMALIZE THE RESULT
  xh = np.array(xh) / max(xh)

  # PLOT WITH LABEL
  ax.plot(xb[1:], xh, label=f"$CDF$({col})")
ax.legend()
plt.title("CDFs of Columns")
plt.show()

这段代码的结果图如下:

要输入您自己的数据,只需将 # GENERATE EXAMPLE DATA 部分替换为 df = pd.read_csv('path/to/sheet.csv')

如果您不清楚示例中的任何内容或是否需要更多解释,请告诉我。