如何根据与输入字符串共享的特征从数据集中获取值

2024-10-06 04:01:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在试验python数据库,并请求它们提供信息。我正在尝试检查数据集(csv文件):

Keyword, Word_num
hello,3
yup,4
yup,5

与输入的字符串共享单词。这是我目前掌握的情况。你知道吗

import csv
import pandas as pd

#creates data set
df = pd.read_csv('Keywords.csv', index_col = 'word_num')

print(df)

print('///////////////////////////////////////////////////////////////////')

#new string for used to check for similatiry
input = 'yup world earthlings'

input = input.split()

#checking for cells andy words in common with 'x'
df = df[df['Keyword'].str.contains('|'.join(input))]

print(df)

到目前为止,这只输出熊猫数据集形式的数据:

Keyword
1     yup

我想做的是让我的输出成为存储的字符串('yup')。你知道吗


Tags: csv数据字符串import信息数据库dffor
2条回答

试试看

results = df[df['Word_num'].str.contains('|'.join(input))].values[0]
for result in results:
    # do something

首先,请以可复制的方式分享您的问题,以便其他人可以创建您的数据,例如:

import pandas as pd

df = pd.DataFrame({'Keyword': ['hello', 'world', 'yup'], 
                   'Word_num': [3, 4, 5]})

其次,不要用保留的特殊关键字命名任何对象。input是Python中的一个特殊术语,用于处理用户输入。因此,请将您的对象命名为my_input或类似的普通名称。你知道吗

my_input = 'yup world earthlings'

现在您要做的是获取这个字符串的每个元素,并检查它们是否存在于您的dfKeyword列中。好吧,做一个循环,就是这样:

for x in my_input.split():
    if x in df['Keyword'].values:
        print(x)

# Output:
# yup
# world

让我知道这是否有帮助或如果你需要进一步的协助。你知道吗

相关问题 更多 >