0

I have a dataframe df1 in python as below:

Type Category
a      1
b      2
c      3
d      4

Expected output:

Type
a/1 
b/2
c/3
d/4

The actual dataframe is way larger than this thus i can't type out every cells for the new dataframe.

How can I extract the columns and output to another dataframe with the '/' seperated? Maybe using some for loop?

1
  • 3
    Try: df['Type']+'/'+df['Category'].astype(str) Commented Jul 2, 2020 at 14:42

1 Answer 1

1

Using str.cat

The right pandas-y way to proceed is by using str.cat

df['Type'] = df.Type.str.cat(others=df.Category.astype(str), sep='/')

others contains the pd.Series to concatenate, and sep the separator to use.

Result

    Type
0   a/1
1   b/2
2   c/3
3   d/4

Performance comparison

%%timeit
df.Type.str.cat(others=df.Category.astype(str), sep='/')
>> 286 µs ± 449 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit
df['Type'] + '/' + df['Category'].astype(str)
>> 348 µs ± 5.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Both solutions give the same result, but using str.cat is about ~20% faster.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh what if i need to add something before? Something like C:/a/1 How can i add the C:/ before it?
In this case, you might want to check this answer: stackoverflow.com/a/11858532/13765085 If you just want a simple way, just go with the first comment left on your question

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.