IIUC eine mögliche Lösung ist strip
wtihespaces:
a=df['Column 1'].str.strip() + df['Column 2'].str.strip()
print (a)
0 A
1 F
2 C
3
dtype: object
Weitere allgemeine Lösung ist der erste Filter Spaltennamen:
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
Und dann müssen Sie Funktion strip
für jede Spalte mit Liste Verständnis anwenden, concat
Ausgabeliste und zuletzt sum
durch Spalten (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
EDIT von Kommentar:
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
Dank jezrael, f oder mein spezielles Problem, die Summe funktioniert nicht, es addiert die Werte, die sie als Float betrachten. Wie kann ich gefilterte Spalten konvertieren astype (str) oder bringen sie in '' und dann Summe –
Ich denke, Sie können '(pd.concat ([df [c] .str.strip() für c in df [Spalten] verwenden. astype (str)], axis = 1) .sum (axis = 1)) ' – jezrael
beide der letzten Lösungen, die diesen Fehler zeigen, wirklich nah, nur etwas fehlt" raise AttributeError (".str accessor" kann nur mit String " AttributeError: Kann nur .str Accessor mit String-Werten verwenden, die np.object_dtype in Pandas verwenden " –