문제 설명
구조화된 배열의 dtype을 변경하면 문자열 데이터가 0이 됩니다. (Changing dtype of structured array zeros out string data)
제 질문은 기본적으로 이번 질문.
문자열 열과 정수 열이 있는 구조화된 배열이 있습니다. dict를 사용하여 문자열을 정수로 대체하지만 해당 열의 유형이 변경되지 않기 때문에 정수는 문자열로 기록됩니다. 열의 dtype을 정수로 변경할 수 있지만 각 문자열의 정수 값 대신 모든 문자열이 0으로 변환됩니다. dtype 변환 중에 정수 값이 손실되지 않도록 열을 어떻게 변경할 수 있습니까?
예시를 만들었습니다.
dat = np.array([('1', 3392),('2', 4159),('1', 1093),('1', 9836)], dtype=[('code', 'U24'),('id', 'i2')])
dat.astype(dtype=[('code', 'i4'), ('id', 'i2')])
하지만 이해할 수 없는 이유로 다음과 같이 실제로 작동합니다.
array([(1, 3392), (2, 4159), (1, 1093), (1, 9836)],
dtype=[('code', '<i4'), ('id', '<i2')])
이것이 내가 원하는 것이다! 대신 어떤 이유로 인해 다음과 같은 결과를 얻었습니다.
array([(0, 3392), (0, 4159), (0, 1093), (0, 9836)],
dtype=[('code', '<i4'), ('id', '<i2')])
ndarray.astype
에서 예상한 결과가 아닌 경우 모든 '코드' 값이 이와 같이 0이 되는 원인은 무엇입니까? 감사. (관련이 있는 경우 Python 3을 사용하고 있습니다.)
편집: dict로 처리한 후 실제 데이터의 스냅샷이 있습니다.
array([('1', 2814), ('1', 1185), ('1', 6836), ('2', 7057), ('1', 5403),...
('1', 1642), ('1', 3967), ('2', 7982), ('1', 6139), ('1', 9934),
('2', 9932), ('1', 3044), ('1', 2769)],
dtype=[('name', '<U24'), ('id', '<i2')])
## 참조 솔루션 #### 방법 1:
My guess is that you're doing this:
baddata = numpy.array([('1', 2814), ('1', 1185), ('1', 6836), ('2', 7057), ('1', 5403),
('1', 1642), ('1', 3967), ('2', 7982), ('1', 6139), ('1', 9934),
('2', 9932), ('1', 3044), ('1', 2769)],
dtype=[('name', '<U24'), ('id', '<i2')])
baddata.astype([('code', 'i4')])
#>>> array([(0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,),
#>>> (0,), (0,)],
#>>> dtype=[('code', '<i4')])
When you're meant to be doing this:
baddata = numpy.array([('1', 2814), ('1', 1185), ('1', 6836), ('2', 7057), ('1', 5403),
('1', 1642), ('1', 3967), ('2', 7982), ('1', 6139), ('1', 9934),
('2', 9932), ('1', 3044), ('1', 2769)],
dtype=[('name', '<U24'), ('id', '<i2')])
baddata.astype([('name', 'i4')])
#>>> array([(1,), (1,), (1,), (2,), (1,), (1,), (1,), (2,), (1,), (1,), (2,),
#>>> (1,), (1,)],
#>>> dtype=[('name', '<i4')])
Note the names.