import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 創建 3 個範例 DataFrame
df1 = pd.DataFrame({‘X’: [1, 2, 3], ‘Y’: [8, 10, 12]})
df2 = pd.DataFrame({‘X’: [1, 2], ‘Y’: [4, 5]})
df3 = pd.DataFrame({‘X’: [1, 2, 3, 4], ‘Y’: [14, 15, 16, 17]})
# 將每個 DataFrame 的行數填充到最大行數
max_rows = max(len(df) for df in [df1, df2, df3])
dfs = []
for df in [df1, df2, df3]:
missing_rows = max_rows – len(df)
df = pd.concat([df, pd.DataFrame(np.nan,
index=np.arange(missing_rows),
columns=df.columns)])
dfs.append(df.reset_index(drop=True)) # 重置 index
# 將所有 DataFrame 組合成一個大的 DataFrame
merged_df = pd.concat(dfs, axis=1, keys=[‘df1’, ‘df2’, ‘df3’])
# 繪製散點圖
ax = merged_df.plot(kind=’scatter’, x=(‘df1’, ‘X’), y=(‘df1’, ‘Y’), color=’red’)
merged_df.plot(kind=’scatter’, x=(‘df2’, ‘X’), y=(‘df2’, ‘Y’), color=’green’, ax=ax)
merged_df.plot(kind=’scatter’, x=(‘df3’, ‘X’), y=(‘df3’, ‘Y’), color=’blue’, ax=ax)
plt.show()
輸出結果:
推薦hahow線上學習python: https://igrape.net/30afN
近期留言