development:python:pandas
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
development:python:pandas [2024/11/09 14:58] – [7. Output] tungnt | development:python:pandas [2024/11/19 14:41] (current) – [5. Group/Sort Data] tungnt | ||
---|---|---|---|
Line 260: | Line 260: | ||
df_groups = df.groupby([' | df_groups = df.groupby([' | ||
+ | |||
+ | df_ut_groups = df_ut_trans.groupby([' | ||
+ | |||
df_groups.sort_values(by=' | df_groups.sort_values(by=' | ||
Line 290: | Line 293: | ||
</ | </ | ||
- | ====== | + | ====== |
<file python> | <file python> | ||
Line 296: | Line 299: | ||
</ | </ | ||
+ | ===== Cập nhật dữ liệu cột của một dataframe từ một dataframe khác ===== | ||
+ | Giả sử: | ||
+ | * df1: DataFrame gốc cần cập nhật dữ liệu | ||
+ | * df2: DataFrame chứa dữ liệu mới để cập nhật | ||
+ | * key: cột khóa chung giữa df1 và df2 | ||
+ | * column_to_update: | ||
+ | |||
+ | **Cách 1:** | ||
+ | |||
+ | Phương thức update() cho phép cập nhật trực tiếp các giá trị trong df1 từ df2 dựa trên các chỉ số hoặc cột chung. | ||
+ | |||
+ | <file python> | ||
+ | import pandas as pd | ||
+ | |||
+ | # Tạo DataFrame ví dụ | ||
+ | df1 = pd.DataFrame({ | ||
+ | ' | ||
+ | ' | ||
+ | }) | ||
+ | |||
+ | df2 = pd.DataFrame({ | ||
+ | ' | ||
+ | ' | ||
+ | }) | ||
+ | |||
+ | # Thiết lập ' | ||
+ | df1.set_index(' | ||
+ | df2.set_index(' | ||
+ | |||
+ | # Cập nhật df1 từ df2 | ||
+ | df1.update(df2) | ||
+ | |||
+ | # Reset index nếu cần thiết | ||
+ | df1.reset_index(inplace=True) | ||
+ | print(df1) | ||
+ | |||
+ | </ | ||
+ | |||
+ | **Cách 2:** | ||
+ | |||
+ | Nếu chỉ muốn cập nhật một cột cụ thể, có thể dùng map() để ánh xạ giá trị từ df2 sang df1. | ||
+ | |||
+ | <file python> | ||
+ | # Tạo DataFrame gốc và DataFrame chứa dữ liệu cập nhật | ||
+ | df1 = pd.DataFrame({ | ||
+ | ' | ||
+ | ' | ||
+ | }) | ||
+ | |||
+ | df2 = pd.DataFrame({ | ||
+ | ' | ||
+ | ' | ||
+ | }) | ||
+ | |||
+ | # Ánh xạ giá trị từ df2 sang df1 dựa trên ' | ||
+ | df1[' | ||
+ | print(df1) | ||
+ | </ | ||
+ | |||
+ | **Cách 3:** | ||
+ | |||
+ | Dùng merge() để kết hợp hai DataFrame dựa trên key, sau đó chọn cột cập nhật từ df2. | ||
+ | |||
+ | <file python> | ||
+ | # Kết hợp df1 và df2 | ||
+ | df_combined = df1.merge(df2[[' | ||
+ | |||
+ | # Cập nhật cột từ df2 nếu có | ||
+ | df_combined[' | ||
+ | |||
+ | # Bỏ cột phụ | ||
+ | df_combined.drop(columns=' | ||
+ | print(df_combined) | ||
+ | </ | ||
+ | ===== Xóa nhiều bản ghi cùng lúc ===== | ||
+ | < | ||
+ | # Xóa các dòng có index là 1 và 3 | ||
+ | df = df.drop(index=[1, | ||
+ | # Xóa các dòng có id là 1 và 3 | ||
+ | df = df[~df[' | ||
+ | </ | ||
development/python/pandas.1731164301.txt.gz · Last modified: 2024/11/09 14:58 by tungnt