【问题标题】:How to create a new column with a value from another column in python如何使用python中另一列的值创建一个新列
【发布时间】:2020-12-17 06:08:48
【问题描述】:

我有一个大的 Excel 表,我的数据如下所示:

type        price
shoes        10 
clothes      20
shoes        30
clothes      40

我想将“30”和“40”值移动到新列,稍后我将删除现有行。我希望它会像这样显示:

type        price     new price
shoes        10        30
clothes      20        40

如何在 python 中实现?

谢谢

【问题讨论】:

  • 到目前为止你的代码是什么?
  • df.assign(temp=df.groupby("type").cumcount()).pivot("type", "temp", "price").rename_axis(columns=None, index=None).set_axis(["price", "new_price"], axis="columns")
  • 请参阅How to Askhelp center

标签: python pandas


【解决方案1】:

你可以试试这个:

df['newprice'] = df.groupby('type')['price'].transform('max')
df = df.drop_duplicates(subset="type", keep="first")
print(df)

输出:

      type  price  newprice
0    shoes     10        30
1  clothes     20        40

【讨论】:

  • 感谢您的帮助!它确实有效,但 newprice 列的结果与价格列的值相同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 2020-03-12
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
相关资源
最近更新 更多