Gururaj Naik Gururaj Naik - 3 months ago 31
Python Question

ValueError: size of tuple must match number of fields while using genfromtxt

import os
import numpy as np
os.getcwd()
os.chdir('C:/Users/Gururaj/Desktop/tech/python/')
data = np.genfromtxt("simple.txt", dtype=None, delimiter=",",
names=str(False))
print(data[0])


=========================error as below======================

this is being done in Jupyter notebook for python 3



ValueError Traceback (most recent call
last)
<ipython-input-34-c2ba85f75012> in <module>()
3 os.getcwd()
4 os.chdir('C:/Users/Gururaj/Desktop/tech/python/')
----> 5 data = np.genfromtxt("simple.txt", dtype=None, delimiter=",",
names=str(False))
6 print(data[0])

C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\npyio.py in
genfromtxt(fname, dtype, comments, delimiter, skip_header, skip_footer,
converters, missing_values, filling_values, usecols, names, excludelist,
deletechars, replace_space, autostrip, case_sensitive, defaultfmt, unpack,
usemask, loose, invalid_raise, max_rows)
1874 ddtype = list(zip(names, column_types))
1875 mdtype = list(zip(names, [np.bool] * len(column_types)))
-> 1876 output = np.array(data, dtype=ddtype)
1877 if usemask:
1878 outputmask = np.array(masks, dtype=mdtype)

ValueError: size of tuple must match number of fields.
===========================================================
Data in file:
this,is,me,learning
monty,pythons,flying,circus
sounds,exciting,but,hmm


Kindly help as I've only started learning Python basics now.

Answer Source

The genfromtxt docs say:

names : {None, True, str, sequence}

you set it to:

In [689]: str(False)
Out[689]: 'False'

In other words, you've told it to name one field 'False'. Hence the mismatch between the number of fields and the number of columns.

I suspect you want names=None, meaning, don't take the field names from the file.