首页 > 解决方案 > 如何根据某个字符串组合是否在同一行的其他列中来更改列中的值?(熊猫)

问题描述

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

我手上有以下东西:

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

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

我的主要问题是我不知道如何告诉 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

解决方案


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

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

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

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

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

希望这可以帮助 :)

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

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

推荐阅读