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 "/".