10

要将前缀/后缀添加到数据框,我通常会执行以下操作。

例如,要添加后缀'@'

df = df.astype(str) + '@'

这基本上将 a 添加'@'到所有单元格值。

我想知道如何删除这个后缀。pandas.DataFrame 类是否有一种方法可以直接从整个 DataFrame 中删除特定的前缀/后缀字符?

我尝试遍历行(作为系列),同时使用rstrip('@')如下:

for index in range(df.shape[0]):
    row = df.iloc[index]
    row = row.str.rstrip('@')

现在,为了制作这个系列的数据框,

new_df = pd.DataFrame(columns=list(df))
new_df = new_df.append(row)

但是,这不起作用。给出空数据框。

我是否缺少一些真正基本的东西?

4

3 回答 3

6

您可以使用applystr.strippd.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 lociloc基于分配。

于 2016-12-13T00:46:54.790 回答
6

您可以使用 applymap 将您的字符串方法应用于每个元素:

df = df.applymap(lambda x: str(x).rstrip('@'))

注意:我不希望这与矢量化方法一样快:pd.Series.str.rstrip即分别转换每一列

于 2016-12-13T00:50:31.693 回答
2

您可以使这变得非常简单,只需使用pandas.DataFrame.replace()方法将所有“@”替换为“”:

df.replace("@", "")

如果您担心“@”不仅在您的值的末尾被替换,您可以使用正则表达式:

df.replace("@$", "", regex=True) 
于 2018-05-04T22:27:43.547 回答