Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

python - Combine Pandas data frame column values into new column

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...