python - 在 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
我认为上面的部分可以解决问题,但我想我错了。任何建议,将不胜感激。谢谢!
解决方案
我认为正在发生的事情是您在迭代它时试图更新 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)
推荐阅读
- regex - 用修改后的正则表达式替换熊猫列中的正则表达式匹配
- mysql - 使用数据库中的正则表达式或通配符删除 wordpress 中的字符串
- django - 使用 Django 实现多对多(无重复)
- python - Python解释器抱怨在当前进程完成引导阶段之前尝试启动新进程
- sql-server - 使用 group by 根据最大其他列获取顶部列?
- c++ - 有没有办法使用 C++ 实时阅读文本?
- laravel - 如何在控制器之间创建验证码会话
- python - python pandas:将字典转换为长格式,计数基于字符串变量的不同值
- c# - 在 C# 中指向或反射到对象
- python - 使用 matplotlib 制作堆栈图时出现“Keyerror”