팬더 시리즈 목록을 numpy 배열로 변환
Aug 20 2020
숫자 목록의 pandas 시리즈 문자열을 numpy 배열로 변환하고 싶습니다. 내가 가진 것은 다음과 같습니다.
ds = pd.Series(['[1 -2 0 1.2 4.34]', '[3.3 4 0 -1 9.1]'])
내 원하는 출력 :
arr = np.array([[1, -2, 0, 1.2, 4.34], [3.3, 4, 0, -1, 9.1]])
지금까지 내가 한 일은 팬더 시리즈를 숫자 목록의 시리즈로 변환하는 것입니다.
ds1 = ds.apply(lambda x: [float(number) for number in x.strip('[]').split(' ')])
하지만에서 ds1
로 이동하는 방법을 모르겠습니다 arr
.
답변
5 ShubhamSharma Aug 20 2020 at 19:52
사용 Series.str.strip+ Series.str.split및 새로운 생성 np.array
과를 dtype=float
:
arr = np.array(ds.str.strip('[]').str.split().tolist(), dtype='float')
결과:
print(arr)
array([[ 1. , -2. , 0. , 1.2 , 4.34],
[ 3.3 , 4. , 0. , -1. , 9.1 ]])
1 Snoopy Aug 20 2020 at 23:48
먼저 Series 개체에서 "[]"를 제거하면 작업이 더 쉬워집니다. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html.
ds1 = ds.str.strip("[]")
# split and exapand the data, conver to numpy array
arr = ds1.str.split(" ", expand=True).to_numpy(dtype=float)
그러면 arr
원하는 형식이 될 것입니다.
array([[ 1. , -2. , 0. , 1.2 , 4.34],
[ 3.3 , 4. , 0. , -1. , 9.1 ]])
그런 다음 Shubham의 대결과 비교하여 약간의 프로파일 링을 수행했습니다.
# Shubham's way
%timeit arr = np.array(ds.str.strip('[]').str.split().tolist(), dtype='float')
332 µs ± 5.72 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# my way
%timeit ds.str.strip("[]").str.split(" ", expand=True).to_numpy(dtype=float)
741 µs ± 4.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
분명히 그의 솔루션은 훨씬 빠릅니다! 건배!