Python: 深入理解 pandas.concat():使用 ignore_index=True 合併 DataFrame 的奧秘

加入好友
加入社群
Python: 深入理解 pandas.concat():使用 ignore_index=True 合併 DataFrame 的奧秘 - 儲蓄保險王
# %%
import pandas as pd

# 創建兩個 DataFrame
df1 = pd.DataFrame({
    'A': [1, 2, 3],
    'B': ['a', 'b', 'c']
})

df2 = pd.DataFrame({
    'A': [4, 5, 6],
    'B': ['d', 'e', 'f']
})

# 不使用 ignore_index=True
result1 = pd.concat([df1, df2])
print("不使用 ignore_index=True:")
print(result1)

輸出結果:

Python: 深入理解 pandas.concat():使用 ignore_index=True 合併 DataFrame 的奧秘 - 儲蓄保險王

合併的df有重複的索引

# %%
import pandas as pd

# 創建兩個 DataFrame
df1 = pd.DataFrame({
    'A': [1, 2, 3],
    'B': ['a', 'b', 'c']
})

df2 = pd.DataFrame({
    'A': [4, 5, 6],
    'B': ['d', 'e', 'f']
})

# 不使用 ignore_index=True
result1 = pd.concat([df1, df2],ignore_index=True)
print("使用 ignore_index=True:")
print(result1)

輸出結果:

Python: 深入理解 pandas.concat():使用 ignore_index=True 合併 DataFrame 的奧秘 - 儲蓄保險王

索引連續且唯一

pd.concat([df1, df2]).reset_index(drop=True)
也有相同效果:

Python: 深入理解 pandas.concat():使用 ignore_index=True 合併 DataFrame 的奧秘 - 儲蓄保險王

關鍵差異

特性ignore_index=True.reset_index(drop=True)
處理方式在合併時直接忽略索引,
生成新索引。
先合併保留索引,
然後重置索引。
效率更高效,
因為一步完成。
稍低,因為多了一步
索引處理。
原始索引是否可用不可用,
索引在合併時
直接被忽略。
drop=True的話,
不可用

原因分析

  1. ignore_index=True 的行為:
    • 在執行 pd.concat() 時,直接忽略原始索引,並重新為結果生成一個從 0 開始的連續索引,無論原索引是否重複。
  2. .reset_index(drop=True) 的行為:
    • 先保留原始索引,合併後的結果中仍然保留重複的索引。
    • 然後執行 .reset_index(drop=True),刪除原始索引並重新生成新的連續索引。

由於兩者最終都會重新生成索引,因此在這種情況下,結果是一樣的。

推薦hahow線上學習python: https://igrape.net/30afN

加入好友
加入社群
Python: 深入理解 pandas.concat():使用 ignore_index=True 合併 DataFrame 的奧秘 - 儲蓄保險王

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡

You may also like...

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *