Pandas 如何将浮点的两列连接到int格式的单个列?
我有两列是浮点型的,我想用“-”连接这两列,结果列应该是int格式。想法是通过Pandas 如何将浮点的两列连接到int格式的单个列?,pandas,Pandas,我有两列是浮点型的,我想用“-”连接这两列,结果列应该是int格式。想法是通过dropna删除缺少的值,转换为整数和字符串,以便可能的连接在一起: a= [10 , 20.0 , 30.0, 45.5, np.nan , 36.3 ] b = [20.0, 10, 30.5, 20, np.nan , 20 ] df = pd.DataFrame({'col1':a, 'col2':b}) s1 = df['col1'].dropna().astype('int').astype(str)
dropna
删除缺少的值,转换为整数和字符串,以便可能的连接在一起:
a= [10 , 20.0 , 30.0, 45.5, np.nan , 36.3 ]
b = [20.0, 10, 30.5, 20, np.nan , 20 ]
df = pd.DataFrame({'col1':a, 'col2':b})
s1 = df['col1'].dropna().astype('int').astype(str)
s2 = df['col1'].dropna().astype('int').astype(str)
s1 = df.loc[df['col1'].notna(), 'col1'].astype('int').astype(str)
s2 = df.loc[df['col2'].notna(), 'col2'].astype('int').astype(str)
备选方案:
df['res2'] = s1 + ' - ' + s2
column1-[10,20.0,30.0,45.5,null,36.3]column2-[20.0,10,30.5,20,null,20]结式-[10-20,20-10,30-30,45-20,null,36-20]你能添加一些示例数据和预期的输出吗?我得到了错误:AttributeError:'Series'对象没有属性'notna'@Sunil-因为ald pandas version,change
notna()
到notnull()
。
df['res2'] = s1 + ' - ' + s2
print (df)
col1 col2 res1 res2
0 10.0 20.0 10 - 20 10 - 20
1 20.0 10.0 20 - 10 20 - 10
2 30.0 30.5 30 - 30 30 - 30
3 45.5 20.0 45 - 20 45 - 20
4 NaN NaN NaN NaN
5 36.3 20.0 36 - 20 36 - 20