python - 使用数据框中多行的信息创建新变量

标签 python pandas dataframe

我有一个如下所示的数据框:

df = pd.DataFrame({"HouseholdNumber": [1, 1, 1, 1, 1, 2, 2], "TypeOfPerson": ["Son", "Daughter", "Daughter", "Parent", "Parent", "Daughter", "Parent"], "Age": [17, 10, 20, 52, 45, 22, 50]})
print(df)
   HouseholdNumber TypeOfPerson  Age
0                1          Son   17   
1                1     Daughter   10   
2                1     Daughter   20  
3                1       Parent   52     
4                1       Parent   45    
5                2     Daughter   22    
6                2       Parent   50      

我想使用多行信息创建一个新变量。这对我来说是一个问题,因为我在使用简单的 df.loc (或 np.where )条件时遇到问题。具体来说,如果该人不是 parent 或年龄组中没有 child ,我希望新变量的值为 no;如果 parent 有 child ,则为 a 18 岁或以下的 child ;如果 parent 有 19 岁至 25 岁之间的 child ,则为 b。如果 parent 有两个年龄段的 child ,则该值仍应为 a。 HouseholdNumber 表示不同的家庭,因此所有条件都应适用于每个 Household。因此,数据框应如下所示:

   HouseholdNumber TypeOfPerson  Age Child
0                1          Son   17    no
1                1     Daughter   10    no
2                1     Daughter   20    no
3                1       Parent   52     a
4                1       Parent   45     a
5                2     Daughter   22    no
6                2       Parent   50     b 

我正在尝试的代码是

df["Child"]=""
for i in df["HouseholdNumber"].unique():
    if (df.loc[df.TypeOfPerson.isin(["Son", "Daughter"]) & (df.Age <= 18)]):
       if (df.loc[(df.TypeOfPerson == "Parent")]):
           df["Child"] = "a"
    elif (df.loc[df.TypeOfPerson.isin(["Son", "Daughter"]) & ((df.Age >= 19) & (df.Age <= 26))]):
       df["Child"] = "b"
    else:
        df["Child"] = "no"

这给了我错误DataFrame的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。我不太确定从这里去哪里,我总是收到此错误。即使没有错误,我怀疑我的代码也不会给出所需的结果。

最佳答案

这里的错误是您使用索引列表访问df.loc,例如:

 df.loc[df.TypeOfPerson.isin(["Son", "Daughter"]) & (df.Age <= 18)]

将返回一个包含多行的数据框。因此,当您将其放在 if 后面时,它会询问如何将该数据帧评估为 bool 值,它是任何单元格True还是所有单元格True

修复错误的一种方法是指定上述操作,或者在您的情况下,您想知道房子是否有 child ,您可以简单地检查切片数据帧的长度:

for i in df["HouseholdNumber"].unique():
    # you didn't use this i in your code
    ppl_in_house = (df.HouseholdNumber == i)
    is_child = df.TypeOfPerson.isin(["Son", "Daughter"])

    num_children = sum(ppl_in_house & is_child)

当然这只是解决问题的一种方法,而不是最好的方法。

关于python - 使用数据框中多行的信息创建新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54259747/

相关文章:

python - 安装 Flask + gunicorn pip 后有意外的依赖

pandas - 使用 Pandas 按日期计数值的频率

python - Pandas:获取重复的索引

python - 表达式在 Windows 上匹配,但在 Mac 上不匹配

python - 为什么我的异常消息不会随着我的 if 语句而改变

python - 使用 Pandas 将 groupby 聚合应用于原始数据框

python - 将一列的每个元素乘以同一数据框中不同列的每个元素

python - Dataframe 中多列的排名

python - 使用索引作为键和日期合并两个数据框

python - 如何在Python中存储目标词