String Formatting using many pandas columns to create a new one

Samovian :

I would like to create a new columns in a pandas DataFrame just like I would do using a python f-Strings or format function. Here is an example:

df = pd.DataFrame({"str": ["a", "b", "c", "d", "e"],
                   "int": [1, 2, 3, 4, 5]})

print(df)

  str  int
0   a    1
1   b    2
2   c    3
3   d    4
4   e    5

I would like to obtain:

  str  int concat
0   a    1   a-01
1   b    2   b-02
2   c    3   c-03
3   d    4   d-04
4   e    5   e-05

So something like:

concat = f"{str}-{int:02d}"

but directly with elements of pandas columns. I imagine the solution is using pandas map, apply, agg but nothing successful.

Many thanks for your help.

jezrael :

Use lsit comprehension with f-strings:

df['concat'] = [f"{a}-{b:02d}" for a, b in zip(df['str'], df['int'])]

Or is possible use apply:

df['concat'] = df.apply(lambda x: f"{x['str']}-{x['int']:02d}", axis=1)

Or solution from comments with Series.str.zfill:

df["concat"] = df["str"] + "-" + df["int"].astype(str).str.zfill(2)

print (df)
  str  int concat
0   a    1   a-01
1   b    2   b-02
2   c    3   c-03
3   d    4   d-04
4   e    5   e-05

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=387035&siteId=1