首页 > 解决方案 > 在 python 数据框中,如果没有被拾取,你如何将值保留为空白?

问题描述

我的代码的功能是从已知值中提取一定容差(100 ppm 容差)内的值。

要提取的数据如下所示:

col1      col2
1000      10000
1050      20000
2000      30000

依此类推(最多 400 行)。下面是从拾取列表中选取的一段代码(值类似于 col1):

for files in file_list:
    df = pd.read_csv(files, engine='python')
    matches = pd.DataFrame(index=pickuplist['mass'],
                        columns=df.set_index(list(df.columns)).index,
                        dtype=bool)
    for index, exp_mass, intensity in df.itertuples():
        matches[exp_mass] = abs(matches.index - exp_mass)/matches.index < ppm/1e6
        if (len(matches[exp_mass])== 0):
            matches[exp_mass] = None
    results3 = matches.any().reset_index(name='a')[matches.any().values]

每个文件的结构都类似于上面显示的示例表(col1、col2 和一个空列)。取货清单如下所示:

col1
1000.04
1050.02
2000.04

运行时的当前代码确实获取了想要的值并将它们输出为:

col1     col2
1000.04  10000
1050.02  20000
2000.04  30000

但是,如果没有收到,我想留空。例如,如果拾取列表在 col1 中包含 1647.58 的值,并且数据中 1647.58 的 100 ppm 容差范围内没有任何内容,则该 1647.58 的匹配数据帧将是空格:

col1     col2
1000.04  10000
1050.02  20000

2000.04  30000

if (len(matches[exp_mass])== 0):
    matches[exp_mass] = None

我认为上面的部分可以解决问题,但我想我错了。任何建议,将不胜感激。谢谢!

标签: pythondataframe

解决方案


我认为正在发生的事情是您在迭代它时试图更新 python 中的变量。这在 python 中是不可能的,检查这个以获得解释,但简化想象你有这个代码

import pandas as pd
import numpy as np

df = pd.DataFrame(np.array([[1000.04, 1000], [1050.02, 2000], [2000.04, 3000]]), columns=('col1', 'col2'))

for index, row in df.iterrows():
    if row['col1'] == 1000.04:
        row['col1'] == np.nan

print(df)

你会认为这会改变第一行的值,但是如果你执行它,你会发现这不会发生。为了更改您的数据框,您需要进行如下更改:

df.loc[df['col1'] == 1000.04, ['col1', 'col2']] = np.nan
print(df)

推荐阅读