我有一个pandas dataframe,如下所示,现在我正在尝试将多个列值映射到新列,基本上是一个多对一映射。
数据帧:
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我不太确定如何处理这个问题,如果我能得到一些帮助,我将不胜感激。
发布于 2019-06-05 22:26:55
如果列表中的所有值都是唯一的,则可以在字典理解中更改字典,将max和join聚合在一起:
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发布于 2019-06-05 22:26:22
你可以groupby dict,然后concat back,在此之前我们需要调整你的dict
d={'x': ['a', 'c', 'd'],'y': ['b', 'e', 'g'],'z': ['f', 'h']}
from itertools import chain
d=dict(chain(*map(dict.items, [dict.fromkeys(y,x) for x,y in d.items()])))
df=pd.concat([df,df.groupby(d,axis=1).max()],axis=1)https://stackoverflow.com/questions/56462445
复制相似问题