How to I get df.to_csv() to stop breaking my row over multiple lines in the output file?

I have a pandas DataFrame which contains a long np array as one of the elements. When I write it to csv using the to_csv() function each row is broken up over multiple lines in the output file. Is there a way to suppress this behavior and get each row of the DataFrame to only take up one line in my output csv?

## Create Example Data Frame
fruit_veg = pd.DataFrame({"category":["fruit","vegetable"],

## Output to csv

The resulting csv file (actually) looks like this:

0,fruit,"['apple' 'pear' 'banana' 'grapefruit' 'watermelon' 'lychee' 'dragonfruit'
1,vegetable,"['asparags' 'cabbage' 'zuchinni' 'broccoli' 'cauliflower' 'carrot'

I want it to look like this:

0,fruit,"['apple' 'pear' 'banana' 'grapefruit' 'watermelon' 'lychee' 'dragonfruit' 'mango']"
1,vegetable,"['asparags' 'cabbage' 'zuchinni' 'broccoli' 'cauliflower' 'carrot' 'celery']"



Prevent this line wrapping by increasing numpy’s linewidth before writing to_csv():



to_csv() writes the array’s __str__() output which includes a line break every 75 characters by default:

linewidth : int, optional

The number of characters per line for the purpose of inserting line breaks (default 75).

fruit_veg.loc[0, 'items'].__str__()

# "['apple' 'pear' 'banana' 'grapefruit' 'watermelon' 'lychee' 'dragonfruit'n 'mango']"

So increase the linewidth with np.set_printoptions() to prevent the 75-char line breaks:

fruit_veg.loc[0, 'items'].__str__()

# "['apple' 'pear' 'banana' 'grapefruit' 'watermelon' 'lychee' 'dragonfruit' 'mango']"

And the csv will come out as desired:


# ,category,items
# 0,fruit,['apple' 'pear' 'banana' 'grapefruit' 'watermelon' 'lychee' 'dragonfruit' 'mango']
# 1,vegetable,['asparags' 'cabbage' 'zuchinni' 'broccoli' 'cauliflower' 'carrot' 'celery']