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 Answers1

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.

Hugolmn
  • 1,530
  • 1
  • 7
  • 20
  • Oh what if i need to add something before? Something like C:/a/1 How can i add the C:/ before it? – Yibin Wong Jul 02 '20 at 15:30
  • In this case, you might want to check this answer: https://stackoverflow.com/a/11858532/13765085 If you just want a simple way, just go with the first comment left on your question – Hugolmn Jul 02 '20 at 15:34