'TypeError: cannot perform reduce with flexible type; does not print the pandas dataframe
Create a program that has a function that takes two integer arguments and prints a Pandas dataframe.
- The two arguments will correspond to the number of rows and number of columns, respectively.
- The dataframe should be filled with random integers from 0 to 100.
- Set your random seed to 56.
randdf.py
import sys
import pandas
import numpy
def randdf(rows=(sys.argv[1]), columns=(sys.argv[2])):
numpy.random.seed(56)
df = pandas.DataFrame(numpy.random.randint(0, 100, size = (rows, columns)))
return df
print(randdf())
Test Case Examples:
python3 randdf.py 4 8
python3 randdf.py 3 5
python3 randdf.py 1 7
Expected Output:
Test Case 1
0 1 2 3 4 5 6 7
0 85 15 64 34 14 87 22 57
1 90 55 24 12 66 43 11 80
2 33 89 10 31 28 37 34 15
3 28 89 19 69 41 66 74 65
Test Case 2
0 1 2 3 4
0 85 15 64 34 14
1 87 22 57 90 55
2 24 12 66 43 11
Test Case 3
0 1 2 3 4 5 6
0 85 15 64 34 14 87 22
Error Message
Traceback (most recent call last):
File "randdf.py", line 10, in <module>
print(randdf())
File "randdf.py", line 7, in randdf
df = pandas.DataFrame(numpy.random.randint(0, 100, size = (rows, columns)))
File "mtrand.pyx", line 747, in numpy.random.mtrand.RandomState.randint
File "_bounded_integers.pyx", line 1234, in numpy.random._bounded_integers._rand_int64
File "<__array_function__ internals>", line 6, in prod
File "/home/codegrade/.local/lib/python3.7/site-packages/numpy/core/fromnumeric.py", line 3031, in prod
keepdims=keepdims, initial=initial, where=where)
File "/home/codegrade/.local/lib/python3.7/site-packages/numpy/core/fromnumeric.py", line 87, in _wrapreduction
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
TypeError: cannot perform reduce with flexible type
Solution 1:[1]
With newer version of numpy and pandas, you need to define dtype like this.
df = pandas.DataFrame(numpy.random.randint(0, 100, size=(10, 20), dtype=np.int32))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thu Ya Kyaw |
