如何将由ones、x、X2生成的numpy浮点型数组转为整数型?
Got it, let's sort this out so you get clean integer arrays instead of those floating-point ones! The root of the problem here is twofold: you're explicitly converting your x values to floats when building xx, and np.ones() defaults to a floating-point data type (usually float64). Since NumPy unifies the dtype of arrays when you concatenate them, even one float array pulls everything to float.
Here are two simple ways to fix this:
1. Create Integer Arrays from the Start (Most Efficient)
Skip converting your lists to floats entirely, and explicitly set the dtype for the ones array to integer. This way all components are integers from the get-go:
import numpy as np x = [10, 23, 25, 30, 37, 40, 46, 52, 60, 65] y = [22, 46, 48, 62, 75, 90, 100, 110, 180, 150] # Create integer arrays directly without float conversion xx = np.array(x, dtype=int) yy = np.array(y, dtype=int) X2 = xx ** 2 # This stays integer since xx is integer # Make the ones array integer type ones = np.ones(len(x), dtype=int) Xq = np.c_[ones, xx, X2] Y = np.array(y).reshape(len(y), 1) print(Xq)
Your output will now look like this (clean integers, no decimal points):
[[ 1 10 100] [ 1 23 529] [ 1 25 625] [ 1 30 900] [ 1 37 1369] [ 1 40 1600] [ 1 46 2116] [ 1 52 2704] [ 1 60 3600] [ 1 65 4225]]
2. Convert Existing Floating-Point Array to Integer
If you need to keep some of your original code (for example, if you use the float arrays elsewhere), you can convert the final Xq array to integer using astype():
# Keep your original code up to creating Xq, then add this line Xq = np.c_[ones, xx, X2].astype(int)
This will convert all the float values to integers (since your original data is whole numbers, there's no loss of precision here).
内容的提问来源于stack exchange,提问作者chetan sharma

