繁体   English   中英

pandas dataframe:从整个数据帧的所有单元格值中添加和删除前缀/后缀

[英]pandas dataframe : add & remove prefix/suffix from all cell values of entire dataframe

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

例如,要添加后缀'@'

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

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

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

我尝试使用rstrip('@')迭代行(作为系列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)

但是,这不起作用。 提供空数据框。

有什么东西真的很基本我错过了吗?

您可以使用applystr.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    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的赋值。

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

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

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

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

df.replace("@", "")

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

df.replace("@$", "", regex=True) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM