天天看點

python dataframe批量将列名加字尾_pandas dataframe:從整個datafram的所有單元格值中添加和删除字首/字尾...

您可以使用pd.Series的apply和str.strip方法: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 [email protected] [email protected] [email protected]

1 [email protected] [email protected] [email protected]

2 [email protected] [email protected] [email protected]

3 [email protected] [email protected] [email protected]

4 [email protected] [email protected] [email protected]

5 [email protected] [email protected] [email protected]

6 [email protected] [email protected] [email protected]

7 [email protected] [email protected] [email protected]

8 [email protected] [email protected] [email protected]

9 [email protected] [email protected] [email protected]

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方法,slice指派隻是文法糖: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']]

這類似于基于pandasloc或iloc的指派。