Pandas 中的条件转置

发布于 2025-01-13 20:01:48 字数 649 浏览 1 评论 0原文

我想在这样的条件下转置列。

df = pd.DataFrame({"Product" : ["A", "A", "A", "B", "B", "B", "C", "C", "C"],
              "Question" : ["What", "When", "Where", "What", "When", "Where", "What", "When", "Where"],
              "Answer" : ["Car", "Friday", "German", "Bike", "Wednesday", "France", "Train", "Sunday", "America"]})

输入图片此处描述

在此处输入图像描述

有人能为这种情况提出有效的解决方案吗?

I wanna transpose columns in conditions like this.

df = pd.DataFrame({"Product" : ["A", "A", "A", "B", "B", "B", "C", "C", "C"],
              "Question" : ["What", "When", "Where", "What", "When", "Where", "What", "When", "Where"],
              "Answer" : ["Car", "Friday", "German", "Bike", "Wednesday", "France", "Train", "Sunday", "America"]})

enter image description here

enter image description here

Can anyone suggest an effective solution for this case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丶情人眼里出诗心の 2025-01-20 20:01:48

使用pivot

out = df.pivot('Product', 'Question', 'Answer') \
        .reset_index().rename_axis(columns=None)
print(out)

# Output
  Product   What       When    Where
0       A    Car     Friday   German
1       B   Bike  Wednesday   France
2       C  Train     Sunday  America

检查如何旋转数据框

Use pivot:

out = df.pivot('Product', 'Question', 'Answer') \
        .reset_index().rename_axis(columns=None)
print(out)

# Output
  Product   What       When    Where
0       A    Car     Friday   German
1       B   Bike  Wednesday   France
2       C  Train     Sunday  America

Check How can I pivot a dataframe

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文