【问题标题】:I'm trying to add a column from one dataframe to another in Python, but not I'm not succcessful我正在尝试在 Python 中将一列从一个数据帧添加到另一个数据帧,但我没有成功
【发布时间】: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

标签: python pandas numpy


【解决方案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

【讨论】:

    【解决方案2】:

    Pandas 正在将数据加入索引中,但您的系列与父数据框的索引不同。相反,您可以为其提供一个 numpy 数据数组。

    cd2['cat_gm'] = cd3['cat_gm'].values
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      相关资源
      最近更新 更多