Add string in a certain position in column in dataframe

Viewed 978

Basically this:

hash = "355879ACB6"
hash = hash[:4] + '-' + hash[4:]
print (hash)
3558-79ACB6

I got this part above from another stackoverflow post here

but for a DataFrame.

I am only able to successfully add strings before and after, like this:

data ['col1'] = data['col1'] + 'teststring'

If I try the solution from the link above [:amountofcharacterstocutafter] to add values at a certain position, which would be something like:

test = data[:2] + 'zz'
print (test)

It does not seem to be applicable, as the [:2] operator works different for dataframes as it does for strings. It cuts the ouput after the first 2 rows.

Goal: I want to add a ' - ' at a certain position. Let's say the input row value is 'TTTT1234', output should be 'TTTT-1234'. For every row.

2 Answers

You can perform the operation you presented on a list but you have a column in a dataframe so its (a bit) different.

So while you can do this:

hash = "355879ACB6"
hash = hash[:4] + '-' + hash[4:]

in order to do this on a dataframe you can do it in at least 2 ways:

consider this dummy df:

    LOCATION    Hash
0   USA         355879ACB6
1   USA         455879ACB6
2   USA         388879ACB6
3   USA         800879ACB6
4   JAPAN       355870BCB6
5   JAPAN       355079ACB6

A. vectorization: the most efficient way

df['new_hash']=df['Hash'].str[:4]+'-'+df['Hash'].str[4:]

    LOCATION    Hash        new_hash
0   USA         355879ACB6  3558-79ACB6
1   USA         455879ACB6  4558-79ACB6
2   USA         388879ACB6  3888-79ACB6
3   USA         800879ACB6  8008-79ACB6
4   JAPAN       355870BCB6  3558-70BCB6
5   JAPAN       355079ACB6  3550-79ACB6

B. apply lambda: intuitive to implement but less attractive in terms of performance

df['new_hash'] = df.apply(lambda x: x['Hash'][:4]+'-'+x['Hash'][4:], axis=1)

Use pd.Series.str. For example:

import pandas as pd
df = pd.DataFrame({
    "c": ["TTTT1234"]
})
df["c"].str[:4] + "-" + df["c"].str[4:] # It will output 'TTTT-1234'

pd.Series.str gives vectorized string functions.

Related