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']
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.
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.
Any string is True , except empty strings. Any number is True , except 0 . Any list, tuple, set, and dictionary are True , except empty ones.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With