1

I have code as below.

def putTogether(self, createCol, fisrtCol, secondCol):
    self.data[createCol] = self.data[fisrtCol].map(str) + '_' + self.data[secondCol].map(str)
    return self.data

This will return strings put together. As an example, I_U. But the number of columns doesn't always have to be 2. It can be arbitrary. So I would like to make it with *args for the flexibility.

So ideally, I wish it to be a form below.

def putTogether(self, createCol, *args):
    ...
    return self.data

Would you someone help me out with this when *args is not in for loop?

Thank you in advance.

junmouse
  • 155
  • 1
  • 9
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). `*args` does not appear in your code, so it's not clear what you want to accomplish. – Prune Apr 27 '21 at 23:40
  • *args == *cols in context – SuperStormer Apr 27 '21 at 23:40
  • Is this in pandas, or numpy array, or base python array? You want to string-concatenate two (dataframe/np.array?/array.array?) columns with a '_' separator. If it's in pandas, it's a duplicate of [Combine two columns of text in pandas dataframe](https://stackoverflow.com/questions/19377969/combine-two-columns-of-text-in-pandas-dataframe) and also [String concatenation of two pandas columns](https://stackoverflow.com/questions/11858472/string-concatenation-of-two-pandas-columns) – smci Apr 27 '21 at 23:42
  • It is dataframe – junmouse Apr 28 '21 at 00:26
  • Then you should have mentioned 'dataframe' and also tagged it [tag:pandas]. But anyway it's a duplicate of the questions I cited. – smci Apr 28 '21 at 00:29

1 Answers1

2

Use a generator expression nested within str.join:

def putTogether(self, createCol, *columns):
    self.data[createCol] = "_".join(self.data[col].map(str) for col in columns)
    return self.data
SuperStormer
  • 4,997
  • 5
  • 25
  • 35