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

1l5u6lss  于 2023-01-24  发布在  其他
关注(0)|答案(2)|浏览(87)

我有一个DataFrame,其值如下所示

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

我希望将“Fruits”列中包含多个单词的值的最后一个单词移到下一行,同时保留“Price”和“Year”中的值。

| 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 |
gupuwyp2

gupuwyp21#

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

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
flvtvl50

flvtvl502#

基于找到多个单词的值中的最后一个分隔符(如果出现),以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

相关问题