我有这两个数据范围CD2和CD3。我想将CAT_GM列从CD3添加到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)
首先,您必须reset_index,
cd2 = cd2.reset_index(drop=True)
cd3 = cd3.reset_index(drop=True)
然后使用pd.concat
将列从一个数据框架复制到另一个数据框架,
new_df = pd.concat([cd2, cd3[['cat_gm']]], axis=1)
现在您得到了所需的东西, print(new_df)
,结果,
cat rand freq _merge cat_gm
0 21 0.102928 2 left_only 11.0
1 21 0.803516 3 left_only 12.0
2 22 0.054483 3 left_only 12.0
3 22 0.724568 4 left_only 12.0
pandas正在连接索引上的数据,但是您的系列索引与父数据框架没有相同的索引。相反,您可以将其馈送为数据。
cd2['cat_gm'] = cd3['cat_gm'].values