[英]How to merge two dataframes based on file name?
我有一個數據幀字典,其中的鍵格式為"Sample_X_####celsius"
。 每個 dataframe 的結構如下:
移位 | 力量 |
---|---|
價值觀 | 價值觀 |
價值觀 | 價值觀 |
價值觀 | 價值觀 |
我還有一個額外的 dataframe 三個列的結構如下:
label | 寬度 | 厚度 |
---|---|---|
樣品_1_200攝氏度 | 11 | 222 |
樣品_1_300攝氏度 | 12 | 223 |
如何將附加 dataframe 的每一行與字典中的 dataframe 的鍵對應於“標簽”條目的每一行結合起來? 我的目標是這樣的:
關鍵字: sample_1_200celsius
移位 | 力量 | label | 寬度 | 厚度 |
---|---|---|---|---|
價值觀 | 價值觀 | 樣品_1_200攝氏度 | 11 | 222 |
價值觀 | 價值觀 | |||
價值觀 | 價值觀 |
如果字典和附加 dataframe 是dictionary
和df
,則可以concat()
具有相應df
行的dictionary
數據幀:
for key in dictionary.keys():
dfs = [dictionary[key], df.loc[df.label == key].reset_index(drop=True)]
dictionary[key] = pd.concat(dfs, axis=1)
給定帶有sample_1_200celsius
和sample_1_300celsius
數據框的dictionary
:
df200 = pd.DataFrame({'displacement': [1,2,3], 'values': [2,4,6]})
df300 = pd.DataFrame({'displacement': [30,20,10], 'values': [60,40,20]})
dictionary = {'sample_1_200celsius': df200, 'sample_1_300celsius': df300}
以及額外的 dataframe df
:
df = pd.DataFrame({'label': ['sample_1_200celsius','sample_1_300celsius'], 'width': [11,12], 'thickness': [222,223]})
# label width thickness
# 0 sample_1_200celsius 11 222
# 1 sample_1_300celsius 12 223
您可以使用loc
索引將每個dictionary
dataframe 與df
中的相應行concat()
:
for key in dictionary.keys():
dfs = [dictionary[key], df.loc[df.label == key].reset_index(drop=True)]
dictionary[key] = pd.concat(dfs, axis=1)
因此, dictionary
值將根據需要更新:
dictionary['sample_1_200celsius']
# displacement values label width thickness
# 0 1 2 sample_1_200celsius 11.0 222.0
# 1 2 4 NaN NaN NaN
# 2 3 6 NaN NaN NaN
dictionary['sample_1_300celsius']
# displacement values label width thickness
# 0 30 60 sample_1_300celsius 12.0 223.0
# 1 20 40 NaN NaN NaN
# 2 10 20 NaN NaN NaN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.