![](/img/trans.png)
[英]Convert array of string (category) to array of int from a pandas dataframe
[英]Python: convert string array to int array in dataframe
我有一個數據框,持續時間是其中一個屬性。 持續時間的內容如下:
array(['487', '346', ..., '227', '17']).
而df.info(),我得到:數據列(共22列):
duration 2999 non-null object
campaign 2999 non-null object
...
現在我想將持續時間轉換為int。 有什么解決方案嗎?
使用astype
:
df['duration'] = df['duration'].astype(int)
計時
使用以下設置生成大型樣本數據集:
n = 10**5
data = list(map(str, np.random.randint(10**4, size=n)))
df = pd.DataFrame({'duration': data})
我得到以下時間:
%timeit -n 100 df['duration'].astype(int)
100 loops, best of 3: 10.9 ms per loop
%timeit -n 100 df['duration'].apply(int)
100 loops, best of 3: 44.3 ms per loop
%timeit -n 100 df['duration'].apply(lambda x: int(x))
100 loops, best of 3: 60.1 ms per loop
df['duration'] = df['duration'].astype(int)
使用int(str)
:
df['duration'] = df['duration'].apply(lambda x: int(x)) #df is your dataframe with attribute 'duration'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.