如何从Python中的CSV文件中的数据绘制几个累积分布函数?

问题描述:

我想创建一个python脚本读取包含安排与整个第一行和每个名字下面的数据样品名称数据的CSV文件,因为这样的:如何从Python中的CSV文件中的数据绘制几个累积分布函数?

sample1,sample2,sample3 
343.323,234.123,312.544 

从数据集我想画每个样品在同一轴上的累积分布函数。使用下面的代码:

import matplotlib.pyplot as plt 
import numpy as np 
import csv 


def isfloat(value): 
    '''make sure sample values are floats 
    (problem with different number of values per sample)''' 
    try: 
     float(value) 
     return True 
    except ValueError: 
     return False 

def createCDFs (dataset): 
    '''create a dictionary with sample name as key and data for each 
    sample as one list per key''' 
    dataset = dataset 
    num_headers = len(list(dataset)) 
    dict_CDF = {} 
    for a in dataset.keys(): 
     dict_CDF["{}".format(a)]= 1. * np.arange(len(dataset[a]))/(len(dataset[a]) - 1) 
    return dict_CDF 

def getdata(): 
    '''retrieve data from a CSV file - file must have sample names in first row 
    and data below''' 

    with open('file.csv') as csvfile: 
     reader = csv.DictReader(csvfile, delimiter = ',') 
     #create a dict that has sample names as key and associated ages as lists 
     dataset = {} 
     for row in reader: 
      for column, value in row.iteritems(): 
       if isfloat(value): 
        dataset.setdefault(column, []).append(value) 
       else: 
        break 
     return dataset 

x = getdata() 
y = createCDFs(x) 

#plot data 
for i in x.keys(): 
    ax1 = plt.subplot(1,1,1) 
    ax1.plot(x[i],y[i],label=str(i)) 


plt.legend(loc='upper left') 
plt.show() 

这得到下面的输出,这仅正确地显示其中一个样品(样本1在图1A中)。

Figure 1A. Only one CDF is displaying correctly (Sample1). B. Expected output

每个样本值的数量不同,我觉得这是我的问题所在。

这真的让我感到困扰,因为我认为解决方案应该相当简单。任何帮助/建议都会有所帮助。我只是想知道我如何正确显示数据。数据可以找到here。预期产出如图1B所示。

+0

什么是SAMPLE2和3的预期CDF? – user2699

+0

我已经添加了在Excel中生成的预期输出的图像 – Ton

+0

我仍然只能看到上一张图像,是否应该有多个链接? – user2699

这是一个更简单的方法。这当然取决于你是否想要使用熊猫。我以前this方法计算暨DIST

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 

data_req = pd.read_table("yourfilepath", sep=",") 
#sort values per column 
sorted_values = data_req.apply(lambda x: x.sort_values()) 

#plot with matplotlib 
#note that you have to drop the Na's on columns to have appropriate 
#dimensions per variable. 

for col in sorted_values.columns: 
    y = np.linspace(0.,1., len(sorted_values[col].dropna())) 
    plt.plot(sorted_values[col].dropna(), y) 

最终,我得到了这个数字,你正在寻找:

enter image description here

+0

太棒了!非常感谢。这很有效,除了数据排序似乎没有工作。我向CSV添加了未排序的示例,并且您的代码未对添加的示例进行排序。但是,一旦我排序了原始数据,它就起作用了有任何想法吗? – Ton

+0

另外。当谈到Python时,我相当不高兴,所以我实际上并不了解熊猫软件包 - 所以非常感谢! – Ton

+0

我找到了排序问题的解决方案。我用以下代码替换了您的排序代码: 'arr = data_req.values' 'arr.sort(axis = 0)' 'data_req = pd.DataFrame(arr,index = data_req.index,columns = data_req.columns) ' – Ton