python - 通过在 pandas 中添加匹配的单元格内容来创建新列

标签 python python-3.x pandas

大家好,当里面有特定的 grep 值时,我需要帮助才能融合包含的列。

举个例子

Species COL1 COL2         COL3           COL4     COL5
SPf_1   4    f_G1         None           None     None
SP1     9    -_Haploviric -_unclassified f_G3     None
SP1     36   k_Orthorn    f_G7           None     None
SP2     90   k_Orthorn    f_G3           p_Pisuvi None
SP3     32   None         None           None     f_83
SP3     2    -_Ribovi     Cattus         None     None
SP4     89   None         None           None     None

然后我想添加一个名为 F_COL 的新列,我在其中为每一行放置带有 f_ pattern 的单元格内容。注意(我只需要检查 COL1-5 而不是也可以有 f_ 模式的 Species 列)。

我应该得到:

Species COL1 COL2         COL3           COL4     COL5 F_COL
SPf_1     4    f_G1         None           None     None f_G1
SP1     9    -_Haploviric -_unclassified f_G3     None f_G3
SP1     36   k_Orthorn    f_G7           None     None f_G7
SP2     90   k_Orthorn    f_G3           p_Pisuvi None f_G3
SP3     32   None         None           None     f_83 f_83
SP3     2    -_Ribovi     Cattus         None     None NA
SP4     89   None         None           None     None NA 

有人有想法吗?

这是字典格式的数据:

{'Species': {0: 'SPf_1', 1: 'SP1', 2: 'SP1', 3: 'SP2', 4: 'SP3', 5: 'SP3', 6: 'SP4'}, 'COL1': {0: 4, 1: 9, 2: 36, 3: 90, 4: 32, 5: 2, 6: 89}, 'COL2': {0: 'f_G1', 1: '-_Haploviric-', 2: 'k_Orthorn', 3: 'k_Orthorn', 4: 'None', 5: '-_Ribovi', 6: 'None'}, 'COL3': {0: 'None', 1: '_unclassified', 2: 'f_G7', 3: 'f_G3', 4: 'None', 5: 'Cattus', 6: 'None'}, 'COL4': {0: 'None', 1: 'f_G3', 2: 'None', 3: 'p_Pisuvi', 4: 'None', 5: 'None', 6: 'None'}, 'COL5': {0: 'None', 1: 'None', 2: 'None', 3: 'None', 4: 'f_83', 5: 'None', 6: 'None'}}

最佳答案

让我们过滤堆叠COL1COL5的列,然后提取 code> f_pattern 字符串后跟 groupby + first on level=0

df.filter(regex='COL[1-5]').stack()\
  .str.extract(r'^(f_.*)', expand=False).groupby(level=0).first()

0    f_G1
1    f_G3
2    f_G7
3    f_G3
4    f_83
5    None
6    None
dtype: object

关于python - 通过在 pandas 中添加匹配的单元格内容来创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66829754/

相关文章:

python - 拆分 Pandas DataFrame,其中一个因子列均匀分布在拆分中

python - 如何从 CSV 检查用户名和密码。文件

python - 您更喜欢使用 del 还是重新分配给 None(垃圾收集)

python - 使用 Python 将 key 发送到游戏中

如果描述包含列表中的短语,Python Pandas 总结分数

python - 如何创建两个独立的 pygame 显示?如果我不能,我如何创建 pygame 的两个实例?

python-3.x - keras 的 lstm 模型的训练和评估精度不同

python - 为什么 .loc 对切片具有包容性行为?

python - 如果我没有得到 float 作为输入,我该如何打印一些东西

Python 将 XLSX 保存到 CSV