【问题标题】:Replacing DataFrame column values - the column row data stored as list替换 DataFrame 列值 - 存储为列表的列行数据
【发布时间】:2021-05-28 00:44:22
【问题描述】:

非常感谢您对如何解决这个难题的贡献, 我在快照中有具有以下结构的数据框,我试图用此列表(myList)中的值替换爱好列中的值,这些值当前不存在于爱好列的每一行中

myList =["Dancing","Climbing,"Singing"]

这是我尝试过的,但我似乎离正确的解决方案还很远。

df.apply(lambda x:df['Hobbies'],(for i in myList: if i not in x : x.append(i)))

感谢您的意见。

【问题讨论】:

    标签: python-3.x dataframe lambda


    【解决方案1】:

    问题在于 lambda 函数的语法。

    正确的代码是:

    import pandas as pd
    
    df = pd.DataFrame({"name":["coe","wood","silla"],
                        "color":["yellow","green","white"],
                        "hobbies":[["swimming","reading"],
                                    ["dancing","reading"],
                                    ["driving","reading"]
                                    ]})
    
    a=["dancing","climbing","singing"]
    
    df["hobbies"]=df["hobbies"].apply(lambda x: x + [i for i in a if i not in x])
    

    在这种情况下,您应该只将函数应用于一列,因此您将当前列替换为新列。

    希望它有效!

    【讨论】:

    • 您的贡献非常有帮助,上述情况的另一种情况是,如果行中有空列表,我想用整个列表替换这样的行 a=["dancing","climbing ","singing"] a=["dancing","climbing","singing"] 什么 lambda 方法会更好。这是一种方法,我正在尝试 df["hobbies"]=df["hobbies"].apply(lambda x: [a for i in x if i is None else x])
    • 如果单元格中的内容是一个空列表,那么我之前发送的代码应该仍然有效,因为空列表将没有任何项目 ["dancing","climbing","singing"] 所以单元格将被填充完整列表。另一方面,如果你在你的单元格中拥有的是一个 NoneType 对象,即None,你必须对我发送的原始行做一些修改:df["hobbies"]=df["hobbies"].apply(lambda x: x + [i for i in a if i not in x] if x is not None else a)。如果你是这个意思,请告诉我。
    • 感谢 Matias 的贡献,真的超级有帮助:)
    【解决方案2】:

    -将单个值替换为单个 DataFrame 列的新值:

    df['column name'] = df['column name'].replace(['old value'],'new value')
    

    -将多个值替换为单个 DataFrame 列的新值:

    df['column name'] = df['column name'].replace(['1st old value','2nd old value',...],'new value')
    

    -将多个值替换为单个 DataFrame 列的多个新值:

    df['column name'] = df['column name'].replace(['1st old value','2nd old value',...],['1st new value','2nd new value',...])
    

    -将单个值替换为整个 DataFrame 的新值:

    df = df.replace(['old value'],'new value')
    

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 2018-02-11
      • 2023-01-19
      • 2014-06-12
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多