Home > Mobile >  Flip order of characters within a string using Python
Flip order of characters within a string using Python

Time:11-18

I wish to flip the order of characters within the 'date' column using Python

Data

id  type  date
aa  hi    2022 Q1
aa  hi    2022 Q2
    

Desired

id  type    date
aa  hi      Q1 2022
aa  hi      Q2 2022

Doing

I believe I can separate and then reverse them?

a = df.split()

Any suggestion is helpful

CodePudding user response:

We can use str.replace with capture groups if wanting to be explicit on pattern:

df['date'] = df['date'].str.replace(r'^(\d{4}) (Q\d)$', r'\2 \1', regex=True)

Or with several str calls (str.split, str, str.join), but this can be slow as it requires several copies of data:

df['date'] = df['date'].str.split().str[::-1].str.join(' ')

df:

   id type     date
0  aa   hi  Q1 2022
1  aa   hi  Q2 2022

Setup:

import pandas as pd

df = pd.DataFrame({
    'id': ['aa', 'aa'],
    'type': ['hi', 'hi'],
    'date': ['2022 Q1', '2022 Q2']
})

CodePudding user response:

You can use Series.map str.format

# split each date on the whitespace and unpacks the resulting list
df['date'] = df['date'].map(lambda date: "{1} {0}".format(*date.split()))

Output

>>> df['date']

0    Q1 2022
1    Q2 2022
Name: date, dtype: object

CodePudding user response:

Indeed, I would do it with list comprehension:

df = pd.DataFrame({'date':['2022 Q1','2022 Q2']})
df['date'] = [' '.join(x.split()[::-1]) for x in df['date']]

Using print(df['date']) Outputs:

0    Q1 2022
1    Q2 2022

CodePudding user response:

df["date"] = df["date"].apply(lambda x: " ".join(reversed(x.split())))

output:

0    Q1 2022
1    Q2 2022
  • Related