IIUC 一种可能的解决方案是strip wtihespaces:
a=df['Column 1'].str.strip() + df['Column 2'].str.strip()
print (a)
0 A
1 F
2 C
3
dtype: object
更通用的解决方案是先过滤列名:
import pandas as pd
df = pd.DataFrame({'ID1':[' A', '', 'C', ' '],
'ID2':[' ', 'F', ' ', ''],
'ID5':['T', 'E', ' ', '']})
print (df)
ID1 ID2 ID5
0 A T
1 F E
2 C
3
List_ID=['ID1','ID2','ID3']
cols = df.columns[df.columns.isin(List_ID)]
print (cols)
Index(['ID1', 'ID2'], dtype='object')
#there are whitespaces
print (df[cols].sum(axis=1))
0 A
1 F
2 C
3
dtype: object
然后您需要为具有列表理解的每一列应用函数 strip,concat 输出列表和最后一个 sum 按列 (axis=1)
print (pd.concat([df[c].str.strip() for c in df[cols]], axis=1).sum(axis=1))
0 A
1 F
2 C
3
通过评论编辑:
import pandas as pd
df = pd.DataFrame({'ID1':[15.3, 12.1, 13.2, 10.0],
'ID2':[7.0, 7.7, 2, 11.3],
'ID5':[10, 15, 3.1, 2.2]})
print (df)
ID1 ID2 ID5
0 15.3 7.0 10.0
1 12.1 7.7 15.0
2 13.2 2.0 3.1
3 10.0 11.3 2.2
List_ID=['ID1','ID2','ID3']
cols = df.columns[df.columns.isin(List_ID)]
print (cols)
Index(['ID1', 'ID2'], dtype='object')
#summed floats
print (df[cols].sum(axis=1))
0 22.3
1 19.8
2 15.2
3 21.3
dtype: float64
#cast float to string and sum
print (df[cols].astype(str).sum(axis=1))
0 15.37.0
1 12.17.7
2 13.22.0
3 10.011.3
dtype: object
#cast float to int, then to str, sum, then removed float 0 by cast to int and last to str
print (df[cols].astype(int).astype(str).sum(axis=1).astype(int).astype(str))
0 157
1 127
2 132
3 1011
dtype: object
#cast float to int, then to str and concanecate by join
print (df[cols].astype(int).astype(str).apply(lambda x: ''.join(x), axis=1))
0 157
1 127
2 132
3 1011
dtype: object