gpt4 book ai didi

python-3.x - 根据列将多个无标题列中的值替换为 0、1、2

转载 作者:行者123 更新时间:2023-12-02 11:07:28 24 4
gpt4 key购买 nike

根据评论进行编辑

背景:这是当前数据框的样子。行标签是原始 Excel 文件中的信息文本。但我希望这个小的数据复制足以解决问题?实际文件大约有 100 列和 200 行。

列标题和第 0 行值按照如下所示的模式重复 - 除了 SalesValidation 文本在每次出现具有现有标题的列时发生变化。

销售前多一列,每行都有文本。为此测试完成的 X 映射。不幸的是,没有找到将文本显示为下面输出的一部分的优雅方法。

 Sales Unnamed: 2  Unnamed: 3  Validation Unnamed: 5 Unnamed: 6
0 Commented No comment Commented No comment
1 x x
2 x x
3 x x

预期输出:根据 X 所在的列(注释/无注释)将 X 替换为 0、1 和 2

 Sales Unnamed: 2  Unnamed: 3  Validation Unnamed: 5 Unnamed: 6
0 Commented No comment Commented No comment
1 0 1
2 2 0
3 1 2

可能的代码:我假设循环看起来像这样:

while in row 9:
if column value = "commented":

replace all "x" with 1

elif row 9 when column valkue = "no comment":

replace all "x" with 2

else:

replace all "x" with 0

但是作为一个Python新手,我不知道如何将其转换为工作代码。我非常感谢所有的支持和帮助。

最佳答案

这是一种方法:

  1. 定义一个函数来替换 x:
import re

def replaceX(col):
cond = ~((col == "x") | (col == "X"))
# Check if the name of the column is undefined
if not re.match(r'Unnamed: \d+', col.name):
return col.where(cond, 0)
else:
# Check what is the value of the first row
if col.iloc[0] == "Commented":
return col.where(cond, 1)
elif col.iloc[0] == "No comment":
return col.where(cond, 2)
return col

或者,如果您的第一行不包含标题列的“注释”或“无注释”,您可以使用不使用正则表达式的解决方案:

def replaceX(col):
cond = ~((col == "x") | (col == "X"))
# Check what is the value of the first row
if col.iloc[0] == "Commented":
return col.where(cond, 1)
elif col.iloc[0] == "No comment":
return col.where(cond, 2)
return col.where(cond, 0)
  • 在 DataFrame 上应用此函数:
  • # Apply the function on every column (axis not specified so equal 0)
    df.apply(lambda col: replaceX(col))

    输出:

      title Unnamed: 2  Unnamed: 3
    0 Commented No comment
    1
    2 0 2
    3 1

    Documentation:

    • Apply: apply a function on every columns/rows depending on the axis
    • Where: check where a condition is met on a series, if it is not met, replace with value specified.

    关于python-3.x - 根据列将多个无标题列中的值替换为 0、1、2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57654372/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com