Note

Numpy (41) 본문

Numpy

Numpy (41)

알 수 없는 사용자 2022. 9. 4. 16:14
728x90

How to create a new column from existing columns of a numpy array?

# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='object')

# Solution
# Compute volume
sepallength = iris_2d[:, 0].astype('float')
petallength = iris_2d[:, 2].astype('float')
volume = (np.pi * petallength * (sepallength**2))/3

# Introduce new dimension to match iris_2d's
volume = volume[:, np.newaxis]

# Add the new column
out = np.hstack([iris_2d, volume])

# View
out[:4]

# output
 array([[b'5.1', b'3.5', b'1.4', b'0.2', b'Iris-setosa', 38.13265162927291],
        [b'4.9', b'3.0', b'1.4', b'0.2', b'Iris-setosa', 35.200498485922445],
        [b'4.7', b'3.2', b'1.3', b'0.2', b'Iris-setosa', 30.0723720777127],
        [b'4.6', b'3.1', b'1.5', b'0.2', b'Iris-setosa', 33.238050274980004]], dtype=object)

'Numpy' 카테고리의 다른 글

Numpy (43)  (0) 2022.09.07
Numpy (42)  (0) 2022.09.06
Numpy (40)  (2) 2022.09.03
Numpy (39)  (0) 2022.08.31
Numpy (38)  (0) 2022.08.30
Comments