在数据帧的子集上使用列表理解进行切片

2024-06-28 14:52:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想运行一个列表理解,在由其他列中的值定义的子集中,在一列中按“-”对名称进行切片。你知道吗

所以在这种情况下:

    category   product_type   name 
0   pc         unit           hero-dominator
1   print      unit           md-ffx605
2   pc         option         keyboard1.x-963

我对“pc”类别和“unit”产品类型感兴趣,因此我希望列表理解仅将“name”列的第一行更改为以下形式:

    category   product_type   name 
0   pc         unit           dominator
1   print      unit           md-ffx605
2   pc         option         keyboard1.x-963

我试过这个:

df['name'].loc[df['product_type']=='unit'] = [x.split('-')[1] for x in df['name'].loc[df['product_type']=='unit']]

但是我得到了“列表索引超出范围”的索引器。你知道吗

非常感谢您的帮助。你知道吗


Tags: namedf列表typeunitproductmdloc
1条回答
网友
1楼 · 发布于 2024-06-28 14:52:03

您可以通过以下方式解决问题,请关注评论并随时提问:

编辑,现在我们考虑“name”列中不能有string元素:

import pandas as pd
import numpy as np


def change(row):
    if row["category"] == "pc" and row["product_type"] == "unit":
        if type(row["name"]) is str:  # check if element is string before split()
            name_split = row["name"].split("-")  # split element
            if len(name_split) == 2:  # it could be name which does not have "-" in it, check it here
                return name_split[1]  # if "-" was in name return second part of split result
            return row["name"]  # else return name without changes

    return row["name"]


# create data frame:
df = pd.DataFrame(
    {
        "category": ["pc", "print", "pc", "pc", "pc", "pc"],
        "product_type": ["unit", "unit", "option", "unit", "unit", "unit"],
        "name": ["hero-dominator", "md-ffx605", "keyboard1.x-963", np.nan, 10.24, None]
    }
)


df["name"] = df.apply(lambda row: change(row), axis=1)  # change data frame here
print(df)

相关问题 更多 >