Identify value across multiple columns in a dataframe that contain string from a list in python

2024/10/14 13:21:49

I have a dataframe with multiple columns containing phrases. What I would like to do is

  1. identify the column (per row observation) that contains a string that exists within a pre-made list of words.
  2. With this information, create a new variable in this dataframe that contains the value in the column that matched with the list. (In this example, "lst" is my list of words)

For example: Starting Dataframe:

starting data

And I would like to end up with this:

final dataframe

New_var is the new variable, and it selected the response in col1 of observation 1 because the "apple" in apple sauce matched with the "apple" in the list. Big oranges would appear for Observation 2 because it matched with "oranges" from the list.

I have tried doing this with list comprehension from this link: List Comprehension, but remain unsuccessful. I wish to do this in python. Any suggestions? I am relatively new to this programming language.

Thank you very much. If I have posted inappropriately or the answer exists somewhere I have not found it, I appreciate any guidance in the right direction.

Answer

Let's take the list of words and data frame as you have mentioned

lst = ['a','m','n','o','p']df = pd.DataFrame({'Observation': [1], 'col1': ['ab'], 'col2': ['dc'], 'col3': ['ef'], 'col4': ['yz']})
dfObservation  col1    col2    col3    col40    1         ab      dc      ef      yz

Check whether values of data frame match with values in the list

df['New_var'] = [x for x in df.values[0] if any(b for b in lst if b in str(x))]
dfObservation  col1    col2    col3    col4    New_var0        1     ab      dc      ef      yz       ab
https://en.xdnf.cn/q/117954.html

Related Q&A

ipython like interpreter for ruby

I come from python background and am learning ruby. IPython is really awesome. I am new to ruby now, and wanted to have some sort of ipython things. As of now am having tough time, going along ruby lin…

Django dynamic verification form

Im trying to create a verification form in Django that presents a user with a list of choices, only one of which is valid.For example, for a user whose favourite pizza toppings includes pineapple and r…

Any method to denote object assignment?

Ive been studying magic methods in Python, and have been wondering if theres a way to outline the specific action of:a = MyClass(*params).method()versus:MyClass(*params).method()In the sense that, perh…

Delete lines found in file with many lines

I have an Excel file (.xls) with many lines (1008), and Im looking for lines that have anything with 2010. For example, there is a line that contains 01/06/2010, so this line would be deleted, leaving …

Combining semaphore and time limiting in python-trio with asks http request

Im trying to use Python in an async manner in order to speed up my requests to a server. The server has a slow response time (often several seconds, but also sometimes faster than a second), but works …

Import of SWIG python module fails with apache

Importing a python mdule throws an exception in django when I run with apache. The same source code works fine with the django development server. I can also import the module from the command line. Th…

Pro-Football-Reference Team Stats XPath

I am using the scrapy shell on this page Pittsburgh Steelers at New England Patriots - September 10th, 2015 to pull individual team stats. For example, I want to pull total yards for the away team (46…

How to delete the last item of a collection in mongodb

I made a program with python and mongodb to do some diaries. Like thisSometimes I want to delete the last sentence, just by typing "delete!" But I dont know how to delete in a samrt way. I do…

Python+kivy+SQLite: How to set label initial value and how to update label text?

everyone,I want to use kivy+Python to display items from a db file. To this purpose I have asked a question before: Python+kivy+SQLite: How to use them together The App in the link contains one screen.…

how to debug ModelMultipleChoiceField [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 7 years ago.Improve…