根据评论编辑
背景:这是当前数据框的样子。行标签是原始 Excel 文件中的信息文本。但我希望这个小的数据复制足以解决问题?实际文件大约有 100 列和 200 行。
列标题和行 #0 值按照如下所示的模式重复 - 除了Sales
or Validation
每次出现具有现有标题的列时,文本都会发生变化。
又一栏before每行都有文字的销售。为此测试完成的 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 替换为 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 新手,我不知道如何将其转换为工作代码。我非常感谢所有的支持和帮助。
这是一种方法:
- 定义一个函数来替换 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))
Output:
title Unnamed: 2 Unnamed: 3
0 Commented No comment
1
2 0 2
3 1
文档:
-
Apply:根据轴对每列/行应用函数
-
Where:检查一系列条件是否满足,如果不满足,则替换为指定的值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)