【问题标题】:How to change a value in a column based on whether or not a certain string combination is in other columns in the same row? (Pandas)如何根据某个字符串组合是否在同一行的其他列中来更改列中的值? (熊猫)
【发布时间】:2018-11-10 05:20:01
【问题描述】:

我是 Pandas 和一般编程的新手。如果这很重要,我正在使用 Anaconda。

我手上有以下东西:

臭名昭著的泰坦尼克号生存数据集。

所以,我的想法是搜索数据框,找到“姓名”列中存在字符串“夫人”的行。并且同时“年龄”将是 NaN(在这种情况下,“年龄”列中的值需要更改为 32)。另外,在单元格中找到“Miss”,另外两列中的值为零。

我的主要问题是我不知道如何告诉 Pandas 替换同一行中的值或删除整行。

    #I decided to collect the indexes of rows with the "Age" value == NaN to further use the
#indices to search through the "Names column." 

        list_of_NaNs = df[df['Age'].isnull()].index.tolist()

            for name in df.Name:
                if "Mrs." in name and name (list_of_NaNs):#if the string combination "Mrs."
        #can be found within the cell...
                    df.loc['Age'] = 32.5 #need to change the value in the
        #column IN THE SAME ROW
                elif "Miss" in name and df.loc[Parch]>0: #how to make a
        #reference to a value IN THE SAME ROW???
                    df.loc["Age"] = 5
                elif df.SibSp ==0 and Parch ==0:
                    df.loc["Age"] = 32.5
                else:
                    #mmm... how do I delete entire row so that it doesn't 
        #interfere with my future actions?

【问题讨论】:

    标签: pandas


    【解决方案1】:

    您可以通过以下方法测试姓名列中是否存在“小姐”或“夫人”:

    df.name.str.contains('Mrs')
    

    因此,以下将为您提供名称中为“夫人”且年龄为 NaN 的行

    df[(df.name.str.contains('Mrs')) & (df.age.isna())]
    

    您可以从这里开始玩不同的案例和任务。

    希望这会有所帮助:)

    并在年龄列中删除带有 NaN 的行:

    df = df.drop(df[df.age.isna()].index)
    

    【讨论】:

    • 为什么,是的,这是巨大的帮助!非常感谢!
    • 如果不是太麻烦,你能不能也展示一下如何删除年龄为NaN..的行?
    • 酷,刚刚在上面答案的最后一行添加了删除行的代码。请接受并作为最终答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 2018-10-15
    • 2021-01-14
    • 2018-02-27
    • 1970-01-01
    • 2020-11-12
    相关资源
    最近更新 更多