Python:基于另一列的条件函数和R创建新列

2024-04-25 02:23:09 发布

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

我正在尝试基于不同列和行的数据生成一些新列。例如,以以下系列为例:

df = pd.Series(['Fruit[edit]','Apple','Orange','Banana','Vegetable[edit]','Celery','Beans','Kale'])

0        Fruit[edit]
1              Apple
2             Orange
3             Banana
4    Vegetable[edit]
5             Celery
6              Beans
7               Kale

我从一个系列开始,其中带有“[edit]”的元素表示类别,其余的是属于该类别的项的名称。我想创建两个新列,一个显示“类别”(即水果或蔬菜),另一个列标题为“名称”,显示属于该类别的项目。你知道吗

最终结果应该是这样的:

Desired Result

    Category    Name
0   Fruit       Apple
1   Fruit       Orange
2   Fruit       Banana
3   Vegetable   Celery
4   Vegetable   Beans
5   Vegetable   Kale

当我们继续这个系列时,我希望代码识别一个新的类别(即以“[edit]”结尾的元素),并将其存储为项目的更新类别,直到到达一个新的类别。你知道吗


Tags: 数据项目名称元素appledf类别edit
3条回答

这可能很难看,但工作:

df = pd.DataFrame(df) #since df is a series
df['Name']=df.groupby(df[0].str.contains('edit').cumsum())[0].apply(lambda x: x.shift(-1))
df=df.dropna().rename(columns={0:'Category'})
df.loc[~df.Category.str.contains('edit'),'Category']=np.nan
df.Category=df.Category.ffill()
df.Category=df.Category.str.split("[").str[0]
print(df)

    Category    Name
0      Fruit   Apple
1      Fruit  Orange
2      Fruit  Banana
4  Vegetable  Celery
5  Vegetable   Beans
6  Vegetable    Kale

你可以用结构提取物要根据关键字的存在提取组

new_df = df.str.extract('(?P<Category>.*\[edit\])?(?P<Name>.*)')\
.replace('\[edit\]', '', regex = True).ffill()\
.replace('', np.nan).dropna()

    Category    Name
1   Fruit   Apple
2   Fruit   Orange
3   Fruit   Banana
5   Vegetable   Celery
6   Vegetable   Beans
7   Vegetable   Kale

用途:

#if necessary convert Series to DataFrame 
df = df.to_frame('Name')
#get rows with edit
mask = df['Name'].str.endswith('[edit]')
#remove edit
df.loc[mask, 'Name'] = df['Name'].str[:-6]
#create Category column
df.insert(0, 'Category', df['Name'].where(mask).ffill())
#remove rows with same values in columns
df = df[~mask].copy()
print (df)
    Category    Name
1      Fruit   Apple
2      Fruit  Orange
3      Fruit  Banana
5  Vegetable  Celery
6  Vegetable   Beans
7  Vegetable    Kale

相关问题 更多 >