如何在python中压缩此定义
我想把这个定义浓缩成更小的东西。 我在考虑一个for循环,但我需要在一个数据帧中的多个列中迭代它。以及创建定义,以便添加要迭代的列列表如何在python中压缩此定义,python,function,dataframe,data-science,Python,Function,Dataframe,Data Science,我想把这个定义浓缩成更小的东西。 我在考虑一个for循环,但我需要在一个数据帧中的多个列中迭代它。以及创建定义,以便添加要迭代的列列表 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 h
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
类似的,它返回一个长字符串,每个列中的值,并将其添加到一列中,列之间用“/”分隔。可能是一些示例数据?什么是
x
?dataframe或给定的行?X当前是dataframe,但是我想更改它,以便它可以处理dataframe中的列列表。例如:X=df['bgp'、'bgp_as'、'bgp_asa']请查看并提供一个包含输入和输出的示例。就目前而言,你想要完成什么还不完全清楚。我不太擅长,但我尽了最大的努力来添加更多关于我需要帮助的信息。谢谢