将Pandas Dataframe中的最后一个单词从一列移动到下一行



我有一个DataFrame,其值如下

| Fruits         | Price | Year |
| Apple Orange   | 50    | 2015 |
| Grape          | 22    | 2018 |
| Orange Mango   | 25    | 2019 |
| Apple Melon    | 30    | 2015 |
| Apple          | 32    | 2020 |

我想从列"水果"中移动包含多个单词的值的最后一个单词。到下一行,同时保留"Price"中的值和";Year"。我希望新的DataFrame像

| Fruits         | Price | Year |
| Apple Orange   | 50    | 2015 |
| Orange         | 50    | 2015 |
| Grape          | 22    | 2018 |
| Orange Mango   | 25    | 2019 |
| Mango          | 25    | 2019 |
| Apple Melon    | 30    | 2015 |
| Melon          | 30    | 2015 |
| Apple          | 32    | 2020 |

拆分Fruits列上的单词,然后只保留至少有2个项目的行,最后将过滤后的数据框连接到原始数据框:

df1 = (df['Fruits'].str.split().loc[lambda x: x.str.len() > 1].str[-1]
.to_frame().join(df.drop(columns='Fruits')))
out = pd.concat([df, df1], axis=0).sort_index(ignore_index=True)
print(out)
# Output
Fruits  Price  Year
0  Apple Orange     50  2015
1        Orange     50  2015
2         Grape     22  2018
3  Orange Mango     25  2019
4         Mango     25  2019
5   Apple Melon     30  2015
6         Melon     30  2015
7         Apple     32  2020

基于查找具有多个单词的值中的最后一个分隔符(如果发生的话)以2单元格序列收集每个条目,然后使用DataFrame.explode将列表/元组转换为行:

df['Fruits'].apply(lambda x: (x, x[x.rfind(' ')+1:]) if ' ' in x else (x, None))
df = df.explode('Fruits').dropna()

Fruits  Price  Year
0  Apple Orange     50  2015
0        Orange     50  2015
1         Grape     22  2018
2  Orange Mango     25  2019
2         Mango     25  2019
3   Apple Melon     30  2015
3         Melon     30  2015
4         Apple     32  2020

最新更新