Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Join treats True as Boolean rather than string

I am writing code to read data from a CSV file to a pandas dataframe and to get the unique values and concatenate them as a string. The problem is that one of the columns contains the values True and False. So while concatenating the values I am getting the error

  sequence item 0: expected str instance, bool found

I want python to treat True as string rather than boolean value.

I have tried many options but none worked.

The full code and a traceback are attached below.

import pandas as pd
df=pd.read_csv('C:/Users/jaiveeru/Downloads/run_test1.csv')
cols=df.columns.tolist()
for i in cols:
    lst=df[i].unique().tolist()
    str1 = ','.join(lst)
    lst2=[str1]
----> 5     str1 = ','.join(lst)
TypeError: sequence item 0: expected str instance, bool found

lst2 should have values ['True,False']

like image 472
Kumar P Avatar asked Mar 26 '19 11:03

Kumar P


People also ask

Does join work on a string?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.

What is a string Boolean?

A Boolean search string is a search tool that allows you to limit or require specific results. Recruiters can use it to find resumes and candidates that most closely match the required qualifications. If you're a recruiter, learning more about Boolean search strings can help you make your search process more efficient.

Is a string true or false Python?

Any string is True , except empty strings. Any number is True , except 0 . Any list, tuple, set, and dictionary are True , except empty ones.

How do you convert Boolean to true in Python?

Method 1: Convert String to Boolean in Python using bool() The bool() method in general takes only one parameter(here x), on which the standard truth testing procedure can be applied. If no parameter is passed, then by default it returns False.


1 Answers

Python 3 does not preform implicit casts. You will need to explicitly cast your booleans to strings.

This can be done easily with map builtin function which applies a function on each item of an iterable and returns the result:

str1 = ','.join(map(str, lst))
like image 80
Tryph Avatar answered Sep 18 '22 17:09

Tryph