Home > Back-end >  One liner for batch changes in pandas column
One liner for batch changes in pandas column

Time:09-22

I have a pandas dataframe, with 10 columns and thousands of rows. The first column is the name of website users, for example:

  Name ...
0 Alex
1 Fred
2 John
3 Chloe
...

I want to change this first column into this:

  Name ...
0 Hi! Alex, mind calling me at 8 p.m.?
1 Hi! Fred, mind calling me at 8 p.m.?
2 Hi! John, mind calling me at 8 p.m.?
3 Hi! Chloe, mind calling me at 8 p.m.?
...

Here, the number 8 will be free input.

In a word, the target string template might be: "Hi! {}, mind calling me at {} p.m.?" - The first placeholder will be the word in the corresponding cell, and the second one for the input number.

I thought of iterating over all rows and manually change the string, but this looks awful and non-pythonian way.

I would like to know if there is a one-liner to do this.

CodePudding user response:

If want use template is necessary loop in apply or map like:

y = 8
df['Name'] = df['Name'].apply(lambda x: f"Hi! {x}, mind calling me at {y} p.m.?")
#alternative
#df['Name'] = df['Name'].map(lambda x: f"Hi! {x}, mind calling me at {y} p.m.?")
print (df)
                                    Name
0   Hi! Alex, mind calling me at 8 p.m.?
1   Hi! Fred, mind calling me at 8 p.m.?
2   Hi! John, mind calling me at 8 p.m.?
3  Hi! Chloe, mind calling me at 8 p.m.?

No apply alternative:

y = 8
df['Name'] = "Hi! "   df['Name']   ", mind calling me at "   str(y)   "p.m.?"
print (df)
                                   Name
0   Hi! Alex, mind calling me at 8p.m.?
1   Hi! Fred, mind calling me at 8p.m.?
2   Hi! John, mind calling me at 8p.m.?
3  Hi! Chloe, mind calling me at 8p.m.?
  • Related