Hướng dẫn dùng pandas pipe python

Để áp dụng các hàm của riêng bạn hoặc của thư viện khác cho Pandas, bạn nên biết ba phương pháp quan trọng. Các phương pháp được thảo luận dưới đây. Phương pháp thích hợp để sử dụng phụ thuộc vào việc liệu hàm của bạn có hoạt động trên toàn bộ DataFrame, theo hàng hoặc theo cột hay không.

  • pipe []
  • apply[]
  • applymap[]

1. Table-wise :

Các hoạt động tùy chỉnh có thể được thực hiện bằng cách chuyển hàm và số lượng tham số thích hợp làm đối số pipe. Do đó, hoạt động được thực hiện trên toàn bộ DataFrame.

Ví dụ: thêm giá trị 2 vào tất cả các phần tử trong DataFrame

def adder[ele1,ele2]:
   return ele1+ele2

Bây giờ chúng ta sẽ sử dụng hàm tùy chỉnh trên DataFrame.

df = pd.DataFrame[np.random.randn[5,3],columns=['col1','col2','col3']]
df.pipe[adder,2]

Toàn bộ code như sau :

import pandas as pd
import numpy as np

def adder[ele1,ele2]:
   return ele1+ele2

df = pd.DataFrame[np.random.randn[5,3],columns=['col1','col2','col3']]
df.pipe[adder,2]
print df.apply[np.mean]

Kết quả :

col1       col2       col3
0   2.176704   2.219691   1.509360
1   2.222378   2.422167   3.953921
2   2.241096   1.135424   2.696432
3   2.355763   0.376672   1.182570
4   2.308743   2.714767   2.130288

2. Hàm hàng hoặc cột wise

Có thể áp dụng các hàm tùy ý dọc theo các trục của DataFrame hoặc Panel bằng cách sử dụng phương thức apply [], giống như các phương pháp thống kê ư, lấy đối số trục tùy chọn. Theo mặc định, việc thực hiện cột , coi mỗi cột như một mảng.

Ví dụ 1 :

import pandas as pd
import numpy as np

df = pd.DataFrame[np.random.randn[5,3],columns=['col1','col2','col3']]
df.apply[np.mean]
print df.apply[np.mean]

Kết quả :

col1   -0.288022
col2    1.044839
col3   -0.187009
dtype: float64

Truyền tham số trục

Ví dụ 2 :

import pandas as pd
import numpy as np

df = pd.DataFrame[np.random.randn[5,3],columns=['col1','col2','col3']]
df.apply[np.mean,axis=1]
print df.apply[np.mean]

Kết quả :

col1    0.034093
col2   -0.152672
col3   -0.229728
dtype: float64

Ví dụ 3: 

import pandas as pd
import numpy as np

df = pd.DataFrame[np.random.randn[5,3],columns=['col1','col2','col3']]
df.apply[lambda x: x.max[] - x.min[]]
print df.apply[np.mean]

Kết quả :

col1   -0.167413
col2   -0.370495
col3   -0.707631
dtype: float64

3. Các phần tử wise

Không phải tất cả các hàm đều có thể được vectơ hóa [không phải mảng NumPy trả về mảng khác cũng như bất kỳ giá trị nào], các phương thức applymap [] trên DataFrame và tương tự map [] trên Series chấp nhận bất kỳ hàm Python nào nhận một giá trị duy nhất và trả về một giá trị duy nhất.

Ví dụ 1:

import pandas as pd
import numpy as np
df = pd.DataFrame[np.random.randn[5,3],columns=['col1','col2','col3']]

# My custom function
df['col1'].map[lambda x:x*100]
print df.apply[np.mean]

Kết quả :

col1    0.480742
col2    0.454185
col3    0.266563
dtype: float64

Ví dụ 2 :

import pandas as pd
import numpy as np

# My custom function
df = pd.DataFrame[np.random.randn[5,3],columns=['col1','col2','col3']]
df.applymap[lambda x:x*100]
print df.apply[np.mean]

Kết quả :

col1    0.395263
col2    0.204418
col3   -0.795188
dtype: float64
DataFrame.drop_duplicates[subset=None, keep='first', inplace=False, ignore_index=False][source]

Return DataFrame with duplicate rows removed.

Considering certain columns is optional. Indexes, including time indexes are ignored.

Parameterssubsetcolumn label or sequence of labels, optional

Only consider certain columns for identifying duplicates, by default use all of the columns.

keep{‘first’, ‘last’, False}, default ‘first’

Determines which duplicates [if any] to keep. - first : Drop duplicates except for the first occurrence. - last : Drop duplicates except for the last occurrence. - False : Drop all duplicates.

inplacebool, default False

Whether to drop duplicates in place or to return a copy.

ignore_indexbool, default False

If True, the resulting axis will be labeled 0, 1, …, n - 1.

New in version 1.0.0.

ReturnsDataFrame or None

DataFrame with duplicates removed or None if inplace=True.

Examples

Consider dataset containing ramen rating.

>>> df = pd.DataFrame[{
...     'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
...     'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
...     'rating': [4, 4, 3.5, 15, 5]
... }]
>>> df
    brand style  rating
0  Yum Yum   cup     4.0
1  Yum Yum   cup     4.0
2  Indomie   cup     3.5
3  Indomie  pack    15.0
4  Indomie  pack     5.0

By default, it removes duplicate rows based on all columns.

>>> df.drop_duplicates[]
    brand style  rating
0  Yum Yum   cup     4.0
2  Indomie   cup     3.5
3  Indomie  pack    15.0
4  Indomie  pack     5.0

To remove duplicates on specific column[s], use subset.

>>> df.drop_duplicates[subset=['brand']]
    brand style  rating
0  Yum Yum   cup     4.0
2  Indomie   cup     3.5

To remove duplicates and keep last occurrences, use keep.

>>> df.drop_duplicates[subset=['brand', 'style'], keep='last']
    brand style  rating
1  Yum Yum   cup     4.0
2  Indomie   cup     3.5
4  Indomie  pack     5.0

Chủ Đề