I'm using pandas and I have a data frame with multiple columns like this:
Col1 CoL2 Col3
A E I
B F J
C G K
Nan H L
D NaN
and so on..
How can I combine these columns into one so that it becomes:
New Col
A
B
C
D
E
F
G
H
I
J
K
L
I also need to get rid of any empty elements (the "NaN"s).
Many thanks in advance!
CodePudding user response:
You can concatenate series together using append()
, and dropna()
to remove the NaNs.
df.Col1.append(df.Col2).append(df.Col3).dropna()
CodePudding user response:
df is original data frame, df_ where the code will append the values.
df_ = pd.DataFrame(columns=['New'])
for ii in df.columns:
xtr = {'New':df[ii].to_list()}
df_=df_.append(pd.DataFrame(xtr),ignore_index=True).dropna()
print(df_)