Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建一个函数,从数据集列中的字符串中提取子字符串_Python_Python 3.x - Fatal编程技术网

Python 创建一个函数,从数据集列中的字符串中提取子字符串

Python 创建一个函数,从数据集列中的字符串中提取子字符串,python,python-3.x,Python,Python 3.x,我有一个数据集,其中一列是文本。我想创建一个函数,根据输入获取字符串(如果此字符串包含此子字符串,则打印该字符串)。我已经写了一个函数,但不确定为什么它不工作 def update_text("selected_text"): for text in df['Activity Name']: if "selected_text" in text: print(text) 我使用以下样本数据进行了测试: import pandas as pd d

我有一个数据集,其中一列是文本。我想创建一个函数,根据输入获取字符串(如果此字符串包含此子字符串,则打印该字符串)。我已经写了一个函数,但不确定为什么它不工作

def update_text("selected_text"):
    for text in df['Activity Name']:
        if "selected_text" in text:
            print(text)

我使用以下样本数据进行了测试:

import pandas as pd

def update_text(selected_text):
    for text in df['Activity Name']:
        if selected_text in text:
            print(text)

df = pd.DataFrame(['hello monkey', 'welcome'], columns=['Activity Name'])

update_text('hello')
hello monkey
请将结果如下:

import pandas as pd

def update_text(selected_text):
    for text in df['Activity Name']:
        if selected_text in text:
            print(text)

df = pd.DataFrame(['hello monkey', 'welcome'], columns=['Activity Name'])

update_text('hello')
hello monkey
关于新问题:

import pandas as pd

def update_text(df, selected_text):
    dfnew = df.loc[df['Activity Name'].str.contains(selected_text)]
    return dfnew

df = pd.DataFrame(['hello monkey', 'welcome'], columns=['Activity Name'])
dfnew = update_text(df, 'hello')

print (dfnew)

你能提供一份请柬吗?示例df和输入。您的答案有效,谢谢。是否有一种方法可以打印整个数据集df并将其分配给新名称,如dfnew@Ardy你能告诉我一个你想要的例子吗?处理数据的方法多种多样,具体取决于目的。定义更新_文本(df,选定_文本):dfnew=[]对于df[‘活动名称’]中的文本:如果在文本中选择了_文本:dfnew.append(df.df[“活动名称”].str.contains(选定_文本)),则根据上面选定的_文本创建一个新的数据框。我有列('活动名称,开始,经度,纬度,类型,成本)。因此,基于“活动”列中的文本。如果选定的_文本位于列“活动名称”的一行中,则过滤数据框,过滤后为其分配一个具有不同名称的新数据框,如dfnew。我希望我没有混淆you@Ardy循环和if语句不需要使用
。您可以在
update\u text
函数中使用我的代码,而不使用
for循环和if语句。