将 pandas 数据帧列值合并到新列中 [英] Combine Pandas data frame column values into new column

查看:131
本文介绍了将 pandas 数据帧列值合并到新列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在和熊猫一起工作,我有一个数据框架,我们可以填充三个值之一:

  ID_1 ID_2 ID_3 
abc NaN NaN
NaN def NaN
NaN NaN ghi
NaN NaN jkl
NaN mno NaN
pqr NaN NaN

我的目标是将这三列合并到数据框中的新列:

  ID_1 ID_2 ID_3 Combined_ID 
abc NaN NaN abc
NaN def NaN def
NaN NaN ghi ghi
NaN NaN jkl jkl
NaN mno NaN mno
pqr NaN NaN pqr

理想情况下,找到列1到3中存在的任何非空值,但是我也可以连接,因为我们只应该为每一行填充三个。谢谢。

  df_note = pd.read_csv(NoteIds.csv)
df_note ['Combined_ID'] =# ID_1 + ID_2 + ID_3


解决方案

求和将连接字符串值,因此您可以调用 fillna ,并传递一个空的str和调用 sum 并通过参数 axis = 1 以行顺序排列:

 在[26]中:

df ['Combined_ID'] = df.fillna('')。sum(axis = 1)
df
Out [26]:
ID_1 ID_2 ID_3 Combined_ID
0 abc NaN NaN abc
1 NaN def NaN def
2 NaN NaN ghi ghi
3 NaN NaN jkl jkl
4 NaN mno NaN mno
5 pqr NaN NaN pqr

如果您只对这3列感兴趣,您可以选择它们:

 在[39]中:

df ['Combined_ID'] = df [['ID_1','ID_2' ,'ID_3']]。fillna('')。sum(axis = 1)
df
输出[39]:
ID_1 ID_2 ID_3 Combined_ID
0 abc NaN NaN abc
1 NaN def NaN def
2 NaN NaN ghi ghi
3 NaN NaN jkl jkl
4 NaN mno NaN mno
5 pqr NaN NaN pqr


I'm working with Pandas and I have a data frame where we can have one of three values populated:

ID_1    ID_2    ID_3
abc     NaN     NaN
NaN     def     NaN
NaN     NaN     ghi
NaN     NaN     jkl
NaN     mno     NaN
pqr     NaN     NaN

And my goal is to combine these three columns into a new columns in my data frame:

ID_1    ID_2    ID_3  Combined_ID
abc     NaN     NaN    abc
NaN     def     NaN    def
NaN     NaN     ghi    ghi
NaN     NaN     jkl    jkl
NaN     mno     NaN    mno
pqr     NaN     NaN    pqr

Ideally it would just find whatever not null value exists in columns 1 through 3, but I could also concatenate since we should only have one of the three populated for each row. Thanks.

df_note = pd.read_csv("NoteIds.csv")
df_note['Combined_ID'] = # ID_1 + ID_2 + ID_3

解决方案

You can use the property that summing will concatenate the string values, so you could call fillna and pass an empty str and the call sum and pass param axis=1 to sum row-wise:

In [26]:

df['Combined_ID'] = df.fillna('').sum(axis=1)
df
Out[26]:
  ID_1 ID_2 ID_3 Combined_ID
0  abc  NaN  NaN         abc
1  NaN  def  NaN         def
2  NaN  NaN  ghi         ghi
3  NaN  NaN  jkl         jkl
4  NaN  mno  NaN         mno
5  pqr  NaN  NaN         pqr

If you're only interested in those 3 columns you can just select them:

In [39]:

df['Combined_ID'] = df[['ID_1','ID_2','ID_3']].fillna('').sum(axis=1)
df
Out[39]:
  ID_1 ID_2 ID_3 Combined_ID
0  abc  NaN  NaN         abc
1  NaN  def  NaN         def
2  NaN  NaN  ghi         ghi
3  NaN  NaN  jkl         jkl
4  NaN  mno  NaN         mno
5  pqr  NaN  NaN         pqr

这篇关于将 pandas 数据帧列值合并到新列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆