Để thêm tiền tố cho tất cả tên cột, dùng phương thức add_prefix().
Nhập thư viện Pandas:
import pandas as pd
Tạo DataFrame 4 cột:
dataFrame = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],
"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],
"Units_Sold": [100, 120, 150, 110, 200, 250]
})
Thêm tiền tố column_ cho mọi cột:
dataFrame.add_prefix('column_')
Ví dụ
import pandas as pd
dataFrame = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],
"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],
"Units_Sold": [100, 120, 150, 110, 200, 250]
})
print("DataFrame ...\n", dataFrame)
print("\nUpdated DataFrame...\n", dataFrame.add_prefix('column_'))
Đầu ra
DataFrame ...
Car Cubic_Capacity Reg_Price Units_Sold
0 BMW 2000 7000 100
1 Lexus 1800 1500 120
2 Tesla 1500 5000 150
3 Mustang 2500 8000 110
4 Mercedes 2200 9000 200
5 Jaguar 3000 6000 250
Updated DataFrame...
column_Car column_Cubic_Capacity column_Reg_Price column_Units_Sold
0 BMW 2000 7000 100
1 Lexus 1800 1500 120
2 Tesla 1500 5000 150
3 Mustang 2500 8000 110
4 Mercedes 2200 9000 200
5 Jaguar 3000 6000 250