0

I have dataframe:

d_test = {
    'c1' : ['a', 'b', np.nan, 'c'],
    'c2' : ['d', np.nan, 'e', 'f'],
    'test': [1,2,3,4],
}
df_test = pd.DataFrame(d_test)

And I want to concatenate columns c1 and c2 in one and have following resulted dataframe:

a 1
b 2
c 4
d 1
e 3
f 4

I tired to use

pd.concat([df_test.c1 , df_test.c2], axis = 0)

to generate such a column but have no idea how to keep 'test' column as well during concationation.

1 Answer 1

1

use melt

df_test.melt('test').dropna()[['value', 'test']]

result:

    value   test
0   a       1
1   b       2
3   c       4
4   d       1
6   e       3
7   f       4
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.