gpt4 book ai didi

python - 将 pandas 列值附加为新列

转载 作者:行者123 更新时间:2023-11-30 22:20:58 25 4
gpt4 key购买 nike

我在 pandas 中有两个数据框,如下所示。

   a  b  c    d
0 1 1 1 0.1
1 1 1 2 0.4
2 1 2 1 0.2
3 1 2 2 0.5


a b c1 c2
0 1 1 0.1 0.4
1 1 2 0.2 0.5

我想知道如何将第一个数据帧转换为第二个数据帧?我尝试使用pivot_table,但除了使用c 中的值创建新列之外,我不确定如何指定保留列a 和b。我还尝试使用 groupby 和 unstack,但这为我创建了一个分层列索引。

最佳答案

如果 set_index 中第一列的值是唯一的,这一点很重要。

然后使用 set_index + unstackcadd_prefix最后reset_indexrename_axis :

df = (df.set_index(['a','b','c'])['d']
.unstack()
.add_prefix('c')
.reset_index()
.rename_axis(None, axis=1))
print (df)
a b c1 c2
0 1 1 0.1 0.4
1 1 2 0.2 0.5

如果前 3 列重复,需要按 groupby 聚合使用 meansum... 等聚合函数,然后解决方案与之前相同或使用 pivot_table :

print (df)
a b c d
0 1 1 1 0.1 <- 1,1,1
1 1 1 2 0.4
2 1 2 1 0.2
3 1 2 2 0.5
4 1 1 1 0.7 <- 1,1,1

df = (df.groupby(['a','b','c'])['d']
.mean()
.unstack()
.add_prefix('c')
.reset_index()
.rename_axis(None, axis=1))

或者:

df = (df.pivot_table(index=['a','b'], columns='c', values='d')
.add_prefix('c')
.reset_index()
.rename_axis(None, axis=1))
<小时/>
print (df)
a b c1 c2
0 1 1 0.4 0.4
1 1 2 0.2 0.5

关于python - 将 pandas 列值附加为新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48721711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com