0

Im looking to condense this definition into something smaller. Im thinking about a for loop but i need to iterate it through multiple columns in a pandas Dataframe. As well as creating the definition so that i can add a list of columns to iterate.

x = pd.DataFrame([['34345','CISA3535'], ['3453', '34345f'], ['34353', '34g46h']], columns=['bgp', 'bgp_as','bgp_asa'])

cols=['bps', 'bgp_as','bgp_asa']

 #this is currently what i have but i need to add 8 more columns to this def, instead i want to iterate the function over a list of columns i give it so i dont have to spend time writing each line. 

def combine_with_nan(x):
   try:
      np.isnan(x['bgp'])
      bgp = ''
   except:
      bgp = x['bgp']
   try:
      np.isnan(x['bgp as'])
      bgp_as = ''
   except:
      bgp_as = x['bgp as']
   try:
      np.isnan(x['bgp asa'])
      bgp_asa = ''
   except:
      bgp_asa = x['bgp asa']
   return bgp + ' |' + bgp_as + '|' + bgp_asa


def combine_with_nan(cols):
   try:
      np.isnan(cols)
      bgp = ''
   except:
      bgp = cols
  return cols + " " + cols + " "+ cols....etc

Something like that, where it returns a long string the values in each column and adds it to one column separated by a "/".

Code Monkey
  • 59
  • 1
  • 12
  • 1
    Perhaps some sample data? What is `x`? The dataframe, or a given row? – Alexander Dec 03 '19 at 19:41
  • X is currently the dataframe, however i would like to change it so that it can work over a list of columns from a dataframe. For example: X=df['bgp','bgp_as','bgp_asa'] – Code Monkey Dec 03 '19 at 19:43
  • Please have a look at [How to make good pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and provide a [mcve] including sample input and output. As it stands, it's not entirely clear what you want to accomplish. – G. Anderson Dec 03 '19 at 20:05
  • Im not to good with SO, but i tried my best to add more info on what I need help with. Thanks – Code Monkey Dec 03 '19 at 20:45

0 Answers0