python:多列pandas数据文件

python:多列pandas数据文件

我正在编写一个Python脚本,它循环N个.SDF填充,使用glob创建它们的列表,对每个文件执行一些计算,然后以pandas数据文件格式存储这些信息。假设我计算每个文件的 4 个不同属性,对于 1000 个填充,预期输出应以 5 列和 1000 行的数据文件格式进行汇总。这是代码示例:

  # make a list of all .sdf filles present in data folder:
dirlist = [os.path.basename(p) for p in glob.glob('data' + '/*.sdf')]

# create empty data file with 5 columns:
# name of the file,  value of variable p, value of ac, value of don, value of wt
df = pd.DataFrame(columns=["key", "p", "ac", "don", "wt"])

# for each sdf file get its name and calculate 4 different properties: p, ac, don, wt
for sdf in dirlist:
        sdf_name=sdf.rsplit( ".", 1 )[ 0 ]
        # set a name of the file
        key = f'{sdf_name}'
        mol = open(sdf,'rb')
        # --- do some specific calculations --
        p = MolLogP(mol) # coeff conc-perm
        ac = CalcNumLipinskiHBA(mol)#
        don = CalcNumLipinskiHBD(mol)
        wt = MolWt(mol)
        # add one line to DF in the following order : ["key", "p", "ac", "don", "wt"]
        df[key] = [p, ac, don, wt]

问题出在脚本的最后一行,需要将所有计算汇总在一行中,并将其与处理后的文件一起附加到 DF 中。最终,对于 1000 个已处理的 SDF 填充,我的 DF 应包含 5 列和 1000 行。

答案1

# make a list of all .sdf filles present in data folder:
dirlist = [os.path.basename(p) for p in glob.glob('data' + '/*.sdf')]

# create empty data file with 5 columns:
# name of the file,  value of variable p, value of ac, value of don, value of wt

# for each sdf file get its name and calculate 4 different properties: p, ac, don, wt

holder = []
for sdf in dirlist:
        sdf_name=sdf.rsplit( ".", 1 )[ 0 ]
        # set a name of the file
        key = f'{sdf_name}'
        mol = open(sdf,'rb')
        # --- do some specific calculations --
        p = MolLogP(mol) # coeff conc-perm
        ac = CalcNumLipinskiHBA(mol)#
        don = CalcNumLipinskiHBD(mol)
        wt = MolWt(mol)
        # add one line to DF in the following order : ["key", "p", "ac", "don", "wt"]
        output_list = pd.Series([key, p, ac, don, wt])
        holder.append(output_list)

df = pd.concat(holder, axis = 1)
df.rename(columns={0:"key", 1:"p", 2:"ac", 3:"don", 4:"wt"], inplace = True)
print(df)

相关内容