Computer >> Máy Tính >  >> Lập trình >> Python

Viết chương trình bằng Python để xóa một hoặc nhiều cột trong DataFrame nhất định

Giả sử, bạn có một khung dữ liệu,

 one  two three
0 1    2    3
1 4    5    6

Và kết quả để loại bỏ một cột là,

 two three
0 2    3
1 5    6

Kết quả cho việc xóa sau nhiều cột là,

 three
0 3
1 6

Để giải quyết vấn đề này, chúng tôi sẽ làm theo các bước dưới đây -

Giải pháp 1

  • Xác định khung dữ liệu

  • Xóa một cột cụ thể bằng phương pháp bên dưới,

del df['one']

Ví dụ

Hãy xem đoạn mã dưới đây để hiểu rõ hơn -

import pandas as pd
data = [[1,2,3],[4,5,6]]
df = pd.DataFrame(data,columns=('one','two','three'))
print("Before deletion\n", df)
del df['one']
print("After deletion\n", df)

Đầu ra

Before deletion
 one two three
0 1    2    3
1 4    5    6
After deletion
 two three
0 2    3
1 5    6

Giải pháp 2

  • Xác định khung dữ liệu

  • Xóa một cột cụ thể bằng cách sử dụng chức năng pop. Nó được định nghĩa bên dưới

df.pop('one')

Ví dụ

import pandas as pd
data = [[1,2,3],[4,5,6]]
df = pd.DataFrame(data,columns=('one','two','three'))
print("Before deletion\n", df)
df.pop('one')
print("After deletion\n", df)

Đầu ra

Before deletion
 one two three
0 1    2    3
1 4    5    6
After deletion
 two three
0 2    3
1 5    6

Giải pháp 3

  • Xác định khung dữ liệu

  • Áp dụng phương pháp dưới đây để giảm nhiều hơn một cột,

df.drop(columns=['one','two'],inplace = True)

Ví dụ

import pandas as pd
data = [[1,2,3],[4,5,6]]
df = pd.DataFrame(data,columns=('one','two','three'))
print("Before deletion\n ", df)
df.drop(columns=['one','two'],inplace = True)
print("After deleting two columns\n", df)

Đầu ra

Before deletion
 one two three
0 1    2    3
1 4    5    6
After deletion
 two three
0 2    3
1 5    6
After deleting two columns
 three
0 3
1 6