您可以使用apply
和str.strip
pd.Series 的方法:
In [13]: df
Out[13]:
a b c
0 dog quick the
1 lazy lazy fox
2 brown quick dog
3 quick the over
4 brown over lazy
5 fox brown quick
6 quick fox the
7 dog jumped the
8 lazy brown the
9 dog lazy the
In [14]: df = df + "@"
In [15]: df
Out[15]:
a b c
0 dog@ quick@ the@
1 lazy@ lazy@ fox@
2 brown@ quick@ dog@
3 quick@ the@ over@
4 brown@ over@ lazy@
5 fox@ brown@ quick@
6 quick@ fox@ the@
7 dog@ jumped@ the@
8 lazy@ brown@ the@
9 dog@ lazy@ the@
In [16]: df = df.apply(lambda S:S.str.strip('@'))
In [17]: df
Out[17]:
a b c
0 dog quick the
1 lazy lazy fox
2 brown quick dog
3 quick the over
4 brown over lazy
5 fox brown quick
6 quick fox the
7 dog jumped the
8 lazy brown the
9 dog lazy the
请注意,您的方法不起作用,因为当您在 for 循环中执行以下分配时:
row = row.str.rstrip('@')
这只是将结果分配给row.str.strip
名称row
而不改变DataFrame
. 这是所有 python 对象和简单名称分配的相同行为:
In [18]: rows = [[1,2,3],[4,5,6],[7,8,9]]
In [19]: print(rows)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [20]: for row in rows:
...: row = ['look','at','me']
...:
In [21]: print(rows)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
要实际更改底层数据结构,您需要使用 mutator 方法:
In [22]: rows
Out[22]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [23]: for row in rows:
...: row.append("LOOKATME")
...:
In [24]: rows
Out[24]: [[1, 2, 3, 'LOOKATME'], [4, 5, 6, 'LOOKATME'], [7, 8, 9, 'LOOKATME']]
请注意,切片分配只是 mutator 方法的语法糖:
In [26]: rows
Out[26]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [27]: for row in rows:
...: row[:] = ['look','at','me']
...:
...:
In [28]: rows
Out[28]: [['look', 'at', 'me'], ['look', 'at', 'me'], ['look', 'at', 'me']]
这类似于pandas
loc
或iloc
基于分配。