【问题标题】:How to merge two dataframes based on file name?如何根据文件名合并两个数据框?
【发布时间】:2021-07-06 11:54:48
【问题描述】:

我有一个数据框字典,其键的格式为"Sample_X_####celsius"。每个数据帧的结构如下:

displacement force
values values
values values
values values

我还有一个额外的数据框,其中三列的结构如下:

label width thickness
sample_1_200celsius 11 222
sample_1_300celsius 12 223

如何将附加数据帧的每一行与字典中谁的键对应于“标签”条目的数据帧结合起来?我的目标是这样的:

密钥:sample_1_200celsius

displacement force label width thickness
values values sample_1_200celsius 11 222
values values
values values

【问题讨论】:

  • pd.concat([df1, df2])。但是你确定你想要一个concat (所以label, width, thickness 只是第一行的非空位?),而不是广播到所有行的连接?你的意图是什么,你想对输出 df 做什么?
  • 可能重复,见Pandas Merging 101
  • 我不太明白什么是具有“Sample_X_####celsius”形式的键的数据帧字典
  • @smci 我无法连接,因为我有大量不同的文件(300+)。我需要一种方法,仅将附加数据框中的一行“匹配”到字典中的每个文件,其键与该行的标签相同。
  • @Ynjxsjmh 键与附加数据框的“标签”行匹配是我想说的。

标签: python pandas join


【解决方案1】:

如果字典和附加数据帧是dictionarydf,您可以concat() dictionary 数据帧与对应的df 行:

for key in dictionary.keys():
    dfs = [dictionary[key], df.loc[df.label == key].reset_index(drop=True)]
    dictionary[key] = pd.concat(dfs, axis=1)

完整示例

给定 dictionarysample_1_200celsiussample_1_300celsius 的数据框:

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}

还有额外的数据框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 索引将concat() 每个dictionary 数据帧与df 中的相应行一起使用:

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

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 2021-09-19
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多