简体   繁体   English

如何在 Pandas 中将数据帧行拆分为两行?

[英]How to split a dataframe row into two rows in Pandas?

I have a dataframe as follows:我有一个数据框如下:

    location   |   amount
    ---------------------------
1   new york          $27.00
2   california        $21.00
3   florida           $19.00
4   texas             $18.00

What I want to do is split the row where Location='California' into two rows where California turns into 'Sacramento' and 'Los Angeles' and the amount (21) gets divided into two, split between the two new rows.我想要做的是将 Location='California' 的行分成两行,其中加利福尼亚变成 'Sacramento' 和 'Los Angeles' 并且数量 (21) 被分成两部分,在两个新行之间分配。

This is the desired result:这是想要的结果:

    location   |   amount
------------------------------
1   new york          $27.00
2   los angeles       $10.50
3   sacramento        $10.50
4   florida           $19
5   texas             $18

Duplicating & Removing复制和删除

cal = df.loc["location" == "california"]

df = df.append({
     "location": "sacramento",
     "amount":  cali["amount"] / 2
      }, ignore_index=True)

df = df.append({
     "location": "los angeles",
     "amount":  cali["amount"] / 2
      }, ignore_index=True)

df.drop(cal.index.to(list))

Sources: https://www.codeforests.com/2020/09/27/pandas-split-one-row-of-data-into-multiple-rows/来源: https : //www.codeforests.com/2020/09/27/pandas-split-one-row-of-data-into-multiple-rows/

Python pandas: fill a dataframe row by row Python pandas:逐行填充数据框

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM