TungNT (Blue)

tungnt.blue@gmail.com

User Tools

Site Tools


development:python:pandas

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
development:python:pandas [2024/11/09 14:58] – [7. Output] tungntdevelopment:python:pandas [2024/11/19 14:41] (current) – [5. Group/Sort Data] tungnt
Line 260: Line 260:
  
 df_groups = df.groupby(['transaction_id']).agg({'transaction_id':'size', 'fee': 'sum', 'amount': 'mean'}).rename(columns={'transaction_id':'count', 'fee': 'fee_total', 'amount': 'amount_avg'}).reset_index() df_groups = df.groupby(['transaction_id']).agg({'transaction_id':'size', 'fee': 'sum', 'amount': 'mean'}).rename(columns={'transaction_id':'count', 'fee': 'fee_total', 'amount': 'amount_avg'}).reset_index()
 +
 +df_ut_groups = df_ut_trans.groupby(['user_id', 'type']).agg({'type':'size', 'request_amount': 'sum', 'fee': 'sum', 'fee_fixed': 'mean', 'fee_flexible': 'mean', 'partner_fee': 'sum'}).rename(columns={'type':'count', 'request_amount': 'gmv', 'fee': 'fee', 'fee_fixed': 'fee_fixed', 'fee_flexible': 'fee_flexible', 'partner_fee': 'partner_fee'}).reset_index()
 +
  
 df_groups.sort_values(by='count', ascending=False) df_groups.sort_values(by='count', ascending=False)
Line 290: Line 293:
 </file> </file>
  
-====== 7. Others ======+====== . Others ======
  
 <file python> <file python>
Line 296: Line 299:
 </file> </file>
  
 +===== 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ột mà bạn muốn cập nhật trong df1
 +
 +**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({
 +    'key': [1, 2, 3, 4],
 +    'column_to_update': ['A', 'B', 'C', 'D']
 +})
 +
 +df2 = pd.DataFrame({
 +    'key': [2, 3],
 +    'column_to_update': ['X', 'Y']
 +})
 +
 +# Thiết lập 'key' làm chỉ số chung để cập nhật
 +df1.set_index('key', inplace=True)
 +df2.set_index('key', inplace=True)
 +
 +# 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)
 +
 +</file>
 +
 +**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({
 +    'key': [1, 2, 3, 4],
 +    'column_to_update': ['A', 'B', 'C', 'D']
 +})
 +
 +df2 = pd.DataFrame({
 +    'key': [2, 3],
 +    'column_to_update': ['X', 'Y']
 +})
 +
 +# Ánh xạ giá trị từ df2 sang df1 dựa trên 'key'
 +df1['column_to_update'] = df1['key'].map(df2.set_index('key')['column_to_update']).fillna(df1['column_to_update'])
 +print(df1)
 +</file>
 +
 +**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[['key', 'column_to_update']], on='key', how='left', suffixes=('', '_new'))
 +
 +# Cập nhật cột từ df2 nếu có
 +df_combined['column_to_update'] = df_combined['column_to_update_new'].combine_first(df_combined['column_to_update'])
 +
 +# Bỏ cột phụ
 +df_combined.drop(columns='column_to_update_new', inplace=True)
 +print(df_combined)
 +</file>
  
 +===== Xóa nhiều bản ghi cùng lúc =====
  
 +<code>
 +# Xóa các dòng có index là 1 và 3
 +df = df.drop(index=[1, 3], inplace=True)
  
 +# Xóa các dòng có id là 1 và 3
 +df = df[~df['id'].isin([1, 3])]
 +</code>
  
development/python/pandas.1731164301.txt.gz · Last modified: 2024/11/09 14:58 by tungnt

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki