【问题标题】:Replace all occurrences but first of a repeating string in a column using pandas使用熊猫替换列中所有出现的重复字符串,但第一个重复字符串
【发布时间】:2022-01-20 12:18:24
【问题描述】:

我在 pandas 数据框中有一列,其中有时有一个重复的字符串:

col1 col2
1 hello
2 bye
3 hello
4 morning
5 night
6 hello

我想做的是修改“hello again”中除第一次出现的“hello”之外的所有内容。所以第一次出现的 hello 保持不变。

col1 col2
1 hello
2 bye
3 hello again
4 morning
5 night
6 hello again

【问题讨论】:

  • 很高兴看到你的思路

标签: python python-3.x pandas dataframe


【解决方案1】:

您可以找到包含"hello" 的行的索引,然后使用pandas.DataFrame.<b>loc</b> 修改除第一个匹配项以外的所有行:

In [1]: import pandas as pd
In [2]: df = pd.DataFrame(data={'col1': [1, 2, 3, 4, 5, 6],
   ...:                         'col2': ['hello', 'bye', 'hello', 'morning', 'night', 'hello']})
In [3]: df
Out[3]: 
   col1     col2
0     1    hello
1     2      bye
2     3    hello
3     4  morning
4     5    night
5     6    hello
In [4]: hello_indices = df.index[df['col2'] == 'hello']
In [5]: hello_indices
Out[5]: Int64Index([0, 2, 5], dtype='int64')
In [6]: df.loc[hello_indices[1:],'col2'] = 'hello again'
In [7]: df
Out[7]: 
   col1         col2
0     1        hello
1     2          bye
2     3  hello again
3     4      morning
4     5        night
5     6  hello again

【讨论】:

  • @OP 请不要接受我的回答 :( 我认为这不是你应该这样做的。
【解决方案2】:

你可以使用

df['col2'] = df['col2'].str.split(expand=True)[0]

split() 默认在空格处拆分,expand=true 创建两个变量而不是两个列表

【讨论】:

    猜你喜欢
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 2018-12-12
    • 2021-07-11
    • 2020-04-09
    相关资源
    最近更新 更多