gpt4 book ai didi

python-3.x - 将多列映射到 Pandas 中的新列

转载 作者:行者123 更新时间:2023-12-02 16:55:52 25 4
gpt4 key购买 nike

我有一个 pandas 数据框,如下所示,现在我正在尝试将多个列值映射到新列,基本上是多对一映射。

数据框:

 a   b   c    d    e    f    g    h
0 2 6 -2 10
1 3 4 7
2 3.5 4.5 8 10.5 8.5
0.5 7.5 6.4 10

我创建了一个字典,显示哪些列属于新列,如下所示。

如果所有列中都有值,则新列应取最大值,如果没有值,则新列应为 NaN。

字典:

 {x : [a, c, d],
{y : [b, e, g],
{z : [f, h]}`

预期数据框:

 a   b   c    d    e    f    g    h    x    y    z
0 2 6 -2 10 2 10 -2
1 3 4 7 3 4 7
2 3.5 4.5 8 10.5 8.5 4.5 8 10.5
0.5 7.5 6.4 10 7.5 10

我不太确定如何解决这个问题,如果我能得到一些帮助,我将不胜感激。

最佳答案

如果列表中的所有值都是唯一的,则可以在字典理解中更改字典,将 maxjoin 聚合在一起:

d =  {'x' : ['a', 'c', 'd'],'y' : ['b', 'e', 'g'], 'z' : ['f', 'h']}

#swap key values in dict
#http://stackoverflow.com/a/31674731/2901002
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}
#convert string repr of numbers to numeric columns
df = df.apply(lambda x: pd.to_numeric(x,errors='coerce'))
df = df.join(df.groupby(d1, axis=1).max())
print (df)
a b c d e f g h x y z
0 0.0 NaN 2.0 NaN 6.0 -2.0 10.0 NaN 2.0 10.0 -2.0
1 NaN 1.0 3.0 NaN NaN NaN 4.0 7.0 3.0 4.0 7.0
2 NaN 2.0 3.5 4.5 8.0 10.5 8.5 NaN 4.5 8.5 10.5
3 0.5 NaN 7.5 NaN 6.4 NaN 10.0 NaN 7.5 10.0 NaN

但如果可能的话,列表中的值应该重复(并非所有列表都是唯一的):

d =  {'x' : ['a', 'c', 'd', 'e', 'f'],'y' : ['b', 'e', 'g', 'a'], 'z' : ['f', 'h']}
for k, v in d.items():
df[k] = df.loc[:, v].max(axis=1)
print (df)
a b c d e f g h x y z
0 0.0 NaN 2.0 NaN 6.0 -2.0 10.0 NaN 6.0 10.0 -2.0
1 NaN 1.0 3.0 NaN NaN NaN 4.0 7.0 3.0 4.0 7.0
2 NaN 2.0 3.5 4.5 8.0 10.5 8.5 NaN 10.5 8.5 10.5
3 0.5 NaN 7.5 NaN 6.4 NaN 10.0 NaN 7.5 10.0 NaN

关于python-3.x - 将多列映射到 Pandas 中的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56462445/

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