簡體   English   中英

如何獲取熊貓數據框中列的唯一長度?

[英]How to get the unique length of a column in a pandas dataframe?

這是csv數據:

staff_id,clock_time,device_id,latitude,longitude
1003,2020/8/27 2:55,d_8,26.39899424,117.7866387
1003,2020/8/26 7:45,d_8,26.39900029,117.7866379
1003,2020/8/26 3:09,d_8,26.40672436,117.8008659
1003,2020/8/26 0:26,d_8,26.89169118,117.1612365
1234567,2020/8/25 9:38,d_8,26.89764297,117.1760012
123456789,2020/5/19 8:29,d_8,24.47420087,118.1085551
1003,2020/5/18 9:06,d_8,24.473124,118.1705641
1003,2020/5/16 7:54,d_8,24.5101858,117.8954614

我使用此代碼獲取數據幀中的staff_id唯一長度:

import pandas as pd

df = pd.read_csv(r'for_test.csv', encoding='utf-8',parse_dates=[1])
staff_id_list = df.staff_id.values.tolist()
staff_id_length_list = [len(str(item)) for item in staff_id_list]
staff_id_length_list = list(set(staff_id_length_list))
print(staff_id_length_list)

輸出為: [9, 4, 7]

雖然輸出是正確的,但是我想用pandas的方法來獲取長度,而不是python的方法。

我該怎么辦?

Series.astypeSeries.str.lenSeries.unique

a = df.staff_id.astype(str).str.len().unique()
print (a)
[4 7 9]

如果需要清單:

L = df.staff_id.astype(str).str.len().unique().tolist()
print (L)
[4, 7, 9]

使用pandas.Series.astypestr.lenunique

df["staff_id"].astype(str).str.len().unique()

輸出:

array([4, 7, 9])

你可以試試下面的——

df['len'] = df['staff_id'].str.len().drop_duplicates()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM