【问题标题】:Replace values in multiple untitled columns to 0, 1, 2 depending on column根据列将多个无标题列中的值替换为 0、1、2
【发布时间】:2019-08-26 08:31:36
【问题描述】:

根据评论编辑

背景:这是当前数据框的样子。行标签是原始 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 替换为 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 新手,我不确定如何将其转换为工作代码。感谢所有支持和帮助。

【问题讨论】:

  • 亲爱的@Erfan,感谢您的评论。我是 python、pandas 和 SO 的新手。不知道如何使用 Xs(图 1)重新创建映射的 DF 作为可复制粘贴的数据。我可以想象具有唯一文本字符串和标题列的数据会更容易。以前我被鼓励分享我的 DF 的图像,我在这里使用了相同的方法。如果您知道更好的方法,我很乐意学习。
  • 要问一个好问题,所有问题都在@Erfan提供的链接中进行了解释,基本上这个想法是根据结构使用头部或/和尾部或/和样本给出数据帧的样本DataFrame(有时所有行看起来都一样,有时有某种顺序)。然后您可以将其打印出来并复制到 stackoverflow 上,以便我们可以使用它。此外,您应该打印您提供的特定 DataFrame 的预期输出作为人们的输入,以查看他们是否给您带来了良好的结果。
  • 如果你在pd.DataFrame() 中放了我们可以复制粘贴的数据,我们复制它就足够了,但是你应该让它作为一个表格出现在stackoverflow 上让我们看到它。这个想法是是否像这样打印它print(df.to_string())并在堆栈溢出时复制粘贴输出,或者如果你在本地运行它,运行df.to_clipboard()并将它粘贴到stackoverflow上(它会自动复制df以便你可以粘贴它)。然后我们可以通过pd.read_clipboard() 复制它,或者如果您也给了我们pd.DataFrame(data),请运行您的代码。
  • @SmileyProd,我不知道可以将粘贴输出复制到此处提出的问题。感谢您提供有用的意见。将尝试看看如何将其添加到问题中并进行相应的修改。
  • @Erfan,现在改版更好了吗?

标签: python-3.x pandas dataframe


【解决方案1】:

这是一种方法:

  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)
  1. 在 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            

文档:

  • Apply:根据轴在每列/行上应用一个函数
  • Where:检查在系列上满足条件的位置,如果不满足,则替换为指定的值。

【讨论】:

  • 效果很好!一百万谢谢。 还有一个问题:我如何编辑代码以使其同时适用于小写和大写Xs?我尝试使用 or 命令,也尝试添加另一个 return 语句,但都没有奏效。
  • 我更新了答案,我也直接创建了一个cond变量让代码更具可读性
  • 试过代码。给我错误:('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index Specification no.')
  • @mvx 我也先放了or 而不是| 现在它已修复,它应该可以正常工作:)
  • 是的,它运行良好。非常非常感谢您的努力! :)
猜你喜欢
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
相关资源
最近更新 更多