Python 3.x 将多个列映射到表中的新列
我有一个熊猫数据框,如下所示,现在我尝试将多个列值映射到新列,基本上是多对一映射 数据帧:Python 3.x 将多个列映射到表中的新列,python-3.x,pandas,Python 3.x,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 我创建了一个字典,显示哪些列属于新列,如
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
我不太清楚如何处理这个问题,如果能得到一些帮助,我将不胜感激 您可以
groupby
dict
,然后concat
返回,在此之前我们需要调整您的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)
如果列表中的所有值都是唯一的,则可以在dict理解中更改字典,将
max
和合并在一起:
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
但如果可能,应重复列表中的值(并非每个列表都唯一):
相关问题@jezrael Man我通常不能像现在这样及时查看网站我正在使用手机很抱歉给您带来不便我认为如果任何列的字符串值正确,max函数就不起作用。@akashbachu是的,字符串对max不起作用,您可以添加df=df.apply(pd.to_numeric,errors=concure,axis=1)
在上述解决方案之前,如果任何列的字符串值正确,我相信max函数不起作用。@akash bachu使用df=df.apply(lambda x:pd.to_numeric(x,errors='concurve'))
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