gpt4 book ai didi

python - 具有重复值的数据框

转载 作者:太空宇宙 更新时间:2023-11-04 07:13:47 24 4
gpt4 key购买 nike

考虑下面的pd.DataFrame

temp = pd.DataFrame({'label_0':[1,1,1,2,2,2],'label_1':['a','b','c',np.nan,'c','b'], 'values':[0,2,4,np.nan,8,5]})

print(temp)
label_0 label_1 values
0 1 a 0.0
1 1 b 2.0
2 1 c 4.0
3 2 NaN NaN
4 2 c 8.0
5 2 b 5.0

我想要的输出是

     label_1    1   2
0 a 0.0 NaN
1 b 2.0 5.0
2 c 4.0 8.0
3 NaN NaN NaN

我已经尝试过 pd.pivot 并与 pd.gropuby 争论不休,但由于重复条目而无法获得所需的输出。非常感谢任何帮助。

最佳答案

d = {}
for _0, _1, v in zip(*map(temp.get, temp)):
d.setdefault(_1, {})[_0] = v

pd.DataFrame.from_dict(d, orient='index')

1 2
a 0.0 NaN
b 2.0 5.0
c 4.0 8.0
NaN NaN NaN

pd.DataFrame.from_dict(d, orient='index').rename_axis('label_1').reset_index()

label_1 1 2
0 a 0.0 NaN
1 b 2.0 5.0
2 c 4.0 8.0
3 NaN NaN NaN

关于python - 具有重复值的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56657365/

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