pandas - 如何根据某个字符串组合是否在同一行的其他列中来更改列中的值?(熊猫)
问题描述
我是 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?
解决方案
以下是测试姓名列中是否存在“小姐”或“夫人”的方法:
df.name.str.contains('Mrs')
因此,以下将为您提供名称中为“夫人”且年龄为 NaN 的行
df[(df.name.str.contains('Mrs')) & (df.age.isna())]
从这里开始,您可以玩不同的案例和任务。
希望这可以帮助 :)
并在年龄列中删除带有 NaN 的行:
df = df.drop(df[df.age.isna()].index)
推荐阅读
- python - 将嵌套列表传递给 sklearn 拆分函数
- mql4 - 如何检查其他 EA 是否在 MQL4 中运行?
- angular - Angular 被动事件监听器
- python - 使用 RPLider (Python) 进行本地化
- tensorflow - 使用重用标志将 tf.variable_scope 转换为 tf.keras.layers.Layer
- c - 如何获取 shstrtab 的字符串?
- python - Python ctypes 将每个错误都变成“free(): invalid pointer”
- sql - 查询以仅选择第一条记录
- php - Laravel 异常处理程序也会记录请求
- ios - 限制设置包中文本字段中的字符数