【问题标题】:How to update value within a column?如何更新列中的值?
【发布时间】:2020-10-25 09:59:16
【问题描述】:

如果数据框的至少一个列包含以下单词之一,我需要更改标签:

check_words=['pit','stop','PIT','STOP','Pit','Stop']

我的数据框中的行示例是:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([['Ferrari was hit by a radio communication blackout' , 'Scuderia Ferrari trying a double pit stop', ' If Ferrari takes nothing else away from the 2019 season, it must learn from its mistakes across the season'], ['We may use the following original news sources for stories', 'Sebastian Vettel insisted he trusts in Ferrari', 'During the recent Grand Prix of Italy, the Scuderia Ferrari team managed to execute one of the fastest pit stops ever performed during a Formula 1 race']]),
                   columns=['Text1', 'Short','Data'])

我创建了一个列标签如下:

df['Label']='No Pit' 识别列是否包含以上列表中的单词。如果它在该列表中包含一个单词,那么我需要更改“Pit”中的标签。

你能告诉我如何改变它吗?

【问题讨论】:

  • 上述输入的预期输出是什么?

标签: python pandas


【解决方案1】:

试试这个:

l = pd.DataFrame(np.vectorize(lambda r: any(x in r for x in check_words))(df.iloc[:3].values))
df['Label'] = l.any(1).agg(lambda x: 'pit' if x else 'not pit')

希望对你有帮助!!!

【讨论】:

  • 使用带有 for 循环的自定义函数比使用内置函数要慢...这种方法将执行时间缩短了 50%
【解决方案2】:

您可以通过创建列表数据框然后将其添加到您的主数据框来做到这一点,这是代码。

import pandas as pd
import numpy as np

check_words=['pit','stop','PIT','STOP','Pit','Stop']

df = pd.DataFrame(np.array([['Ferrari was hit by a radio communication blackout' , 'Scuderia Ferrari trying a double pit stop', ' If Ferrari takes nothing else away from the 2019 season, it must learn from its mistakes across the season'], ['We may use the following original news sources for stories', 'Sebastian Vettel insisted he trusts in Ferrari', 'During the recent Grand Prix of Italy, the Scuderia Ferrari team managed to execute one of the fastest pit stops ever performed during a Formula 1 race']]),columns=['Text1', 'Short','Data'])

df['Label'] = pd.DataFrame(check_words)

print(df)

输出

0   Ferrari was hit by a radio communication blackout   Scuderia Ferrari trying a double pit stop   If Ferrari takes nothing else away from the 2...    pit
1   We may use the following original news sources...   Sebastian Vettel insisted he trusts in Ferrari  During the recent Grand Prix of Italy, the Scu...   stop

【讨论】:

【解决方案3】:

我使用自己的函数 (chk_word) 来检查和编写“check_words”。

def chk_word(row):
    for c in check_words:
        if row.str.contains(c).any():
            return c
df['Label'] = df.apply(chk_word, axis=1)
df
Text1   Short   Data    Label
0   Ferrari was hit by a radio communication blackout   Scuderia Ferrari trying a double pit stop   If Ferrari takes nothing else away from the 2...    pit
1   We may use the following original news sources...   Sebastian Vettel insisted he trusts in Ferrari  During the recent Grand Prix of Italy, the Scu...   pit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    相关资源
    最近更新 更多