我是熊猫和编程领域的新手。如果需要的话,我正在使用Anaconda。
我手上有以下东西:
臭名昭著的泰坦尼克号生存数据集。
所以,我的想法是搜索数据框,在“名称”列中的字符串“ Mrs”中找到行。 AND同时,“年龄”将为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?
答案 0 :(得分:0)
在这里,您可以测试名称栏中是否显示“小姐”或“太太”:
df.name.str.contains('Mrs')
因此,下面将为您提供名称为“ Mrs”且年龄为NaN的行
df[(df.name.str.contains('Mrs')) & (df.age.isna())]
您可以从这里开始处理不同的案例和任务。
希望这会有所帮助:)
并在年龄列中删除带有NaN的行:
df = df.drop(df[df.age.isna()].index)