Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chuyển vị (transpose) index và cột DataFrame Python pandas (3 cách)

Giả sử bạn muốn hoán đổi hàng thành cột, cột thành hàng (transpose) cho DataFrame.

Cách 1: List comprehension (thuật toán cơ bản)

import pandas as pd
data = [[1,2,3],[4,5,6]]
df = pd.DataFrame(data)
print("Gốc:\n", df)

result = [[data[i][j] for i in range(len(data))] for j in range(len(data[0]))]
df2 = pd.DataFrame(result)
print("\nTranspose (list comp):\n", df2)

Cách 2: df.T hoặc df.transpose() (khuyên dùng)

print("\nTranspose (df.T):\n", df.T)
# hoặc
print("\nTranspose (df.transpose()):\n", df.transpose())

Cách 3: zip(*data) (unpacking)

result = zip(*data)
df2 = pd.DataFrame(result)
print("\nTranspose (zip):\n", df2)

Kết quả (cả 3 cách)

Gốc:
   0  1  2
0  1  2  3
1  4  5  6

Transpose:
   0  1
0  1  4
1  2  5
2  3  6

So sánh:

  • df.T / df.transpose(): Nhanh nhất, tối ưu, bảo toàn dtype.
  • zip(*data): Pythonic, hoạt động trên list of lists trước khi tạo DataFrame.
  • List comprehension: Minh họa thuật toán, chậm, dễ lỗi với dữ liệu lớn.