我們如何計算熊貓資料框中字串中唯一字符的數量?我在列中有這樣的資料:
| 數字 | 電話(型別字串) |
|---|---|
| 1 | 100012 |
| 2 | 121111 |
| 3 | 121127 |
| 4 | 465222 |
我想添加另一列,其中提到每個字串中唯一字符的長度。
預期輸出:
| 數字 | 電話(型別字串) | unique_characters |
|---|---|---|
| 1 | 100012 | 3 |
| 2 | 121111 | 2 |
| 3 | 121127 | 3 |
| 4 | 465222 | 4 |
到目前為止,我已經嘗試過:
df['unique_characters'] = len(set(df['phone']))
但是,上面的代碼給了我這個結果:
| 數字 | 電話(型別字串) | unique_characters |
|---|---|---|
| 1 | 100012 | 159378 |
| 2 | 121111 | 159378 |
| 3 | 121127 | 159378 |
| 4 | 465222 | 159378 |
請幫忙。
uj5u.com熱心網友回復:
沒有拉姆達:
>>> df['phone'].apply(set)
0 {0, 1, 2}
1 {1, 2}
2 {7, 1, 2}
3 {5, 6, 4, 2}
Name: phone, dtype: object
和
>>> df['phone'].apply(set).apply(len)
0 3
1 2
2 3
3 4
Name: phone, dtype: int64
注意:正如@mozway 正確指出的那樣,雙應用比使用 lambda 的單應用慢,或者比專用函式更好。但是,如果你正在尋找存盤兩者的一套獨特的數字和它們的長度,然后你會做一個.apply(set)針對前者,.apply(len)就可以了后者。
定時
n = 1_000_000
df = pd.DataFrame({'phone': np.random.randint(1e4, 1e9, size=n).astype(int).astype(str)})
%timeit df['phone'].apply(set).apply(len)
# 1.17 s ± 1.76 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit df['phone'].apply(lambda x: len(set(x)))
# 738 ms ± 4.87 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
def nu(x):
return len(set(x))
%timeit df['phone'].apply(nu)
# 698 ms ± 1.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
uj5u.com熱心網友回復:
您可以使用len np.unique:
df['unique_characters'] = df['phone'].apply(lambda x: len(np.unique([*x])))
輸出:
Number phone unique_characters
0 1 100012 3
1 2 121111 2
2 3 121127 3
3 4 465222 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/392037.html
