Mary
Mary

Reputation: 797

select all value with single string when have multiple values for search result of `isin` from pandas dataframe

Select all values with one string when have multiple values of search result using isin from pandas dataframe, this example result should be "'40','50','60','70','80'"

python code

d = [['b', '1', 40],
    ['b', '2', 50],
    ['b', '3', 60],
    ['b', '4', 70],
    ['b', '5,6', 80]]

p = pd.DataFrame(d)
p.columns = ['one', 'two', 'three']
p.loc[p['one'].isin(["b"])]['three']

Execution Result

    one two three
0   b   1   40
1   b   2   50
2   b   3   60
3   b   4   70
4   b   5,6 80

expected result

 p.loc[p['one'].isin(["b"])]['three'][*]
 
"'40','50','60','70','80'"

Upvotes: 0

Views: 154

Answers (1)

heretolearn
heretolearn

Reputation: 6555

You could try something like this :

# get the numbers to a list
numlist = p.loc[p['one'].isin(["b"])]['three'].tolist()

# concatenate the list to get the desired format
",".join(f"'{num}'" for num in numlist)

Output:

"'40','50','60','70','80'"

Upvotes: 1

Related Questions