【发布时间】:2017-12-22 01:26:41
【问题描述】:
我有这两个数据帧,cd2 和 cd3。我想将 cd3 中的 cat_gm 列添加到 cd2:
cd2
cat rand freq _merge
7 21 0.810730 2 left_only
8 21 0.591324 3 left_only
12 22 0.083941 3 left_only
13 22 0.378123 4 left_only
cd3
cat freq cat_gm _merge
14 11 2 11.0 right_only
15 12 3 12.0 right_only
16 12 4 12.0 right_only
17 12 5 12.0 right_only
为了达到我的目的,我尝试了以下代码:
cd2['cat_gm']=pd.Series(cd3['cat_gm'])
cd2
cat rand freq _merge cat_gm
7 21 0.810730 2 left_only NaN
8 21 0.591324 3 left_only NaN
12 22 0.083941 3 left_only NaN
13 22 0.378123 4 left_only NaN
如您所见,我得到的只是缺失值。我想要这个:
cd2['cat_gm']=pd.Series(cd3['cat_gm'])
cd2
Out[13]:
cat rand freq _merge cat_gm
7 21 0.810730 2 left_only 11.0
8 21 0.591324 3 left_only 12.0
12 22 0.083941 3 left_only 12.0
13 22 0.378123 4 left_only 12.0
我哪里做错了?
以下代码是我最初创建 cd2 和 cd3 的方式:
import pandas as pd
import numpy as np
a=pd.DataFrame({'cat':[11,12,21,22],'freq':[2,3,4,5]})
b=pd.DataFrame({'cat':[11,12,21,22],'freq':[3,6,2,3]})
c=pd.Series.to_frame(np.repeat(a['cat'],a['freq']))
d=pd.Series.to_frame(np.repeat(b['cat'],b['freq']))
c['rand']=np.random.uniform(0,1,len(c.index))
c['freq']=c.groupby('cat').cumcount()
d['freq']=d.groupby('cat').cumcount()
c.sort_values(by=['rand'])
d['cat_gm']=d['cat']
cd=pd.merge(c,d,on=['cat','freq'],how='outer',indicator=True)
cd1=cd[cd._merge=='both']
cd2=cd[pd.isna(cd['cat_gm'])==True]
cd2=cd2.drop(['cat_gm'],axis=1)
cd3=cd[pd.isna(cd['rand'])==True]
cd3=cd3.drop(['rand'],axis=1)
【问题讨论】:
-
如果你在 Pandas 中为一列分配一个系列,它将根据索引进行分配。因为您的索引不匹配,所以它使用 NaN。
-
谢谢,已修复。
cat_gm=cd3['cat_gm'].as_matrix() cd2['cat_gm']=cat_gm