【问题标题】:I have two dataframes. I wanted to compare header of one dataframe with the content of one column in another dataframe我有两个数据框。我想将一个数据帧的标题与另一个数据帧中一列的内容进行比较
【发布时间】:2019-07-20 10:31:25
【问题描述】:

我有两个数据框。在第一个数据框中,有一个列名 testname,其中有 88 个测试,在第二个数据框中,我将这些测试名称作为标题。所以现在我想将第一个数据帧中的 testname 列的内容与第二个数据帧的标题进行比较。如果 testname 可用,我想检查第一个数据帧中的每个 id 我想在第二个数据帧中添加该特定的 testname 值。

我已经通过迭代两个数据框进行了尝试,并且第一步也完成了 id 的匹配,但我不知道如何同时比较内容和标题

【问题讨论】:

  • 请提供每个数据框的示例,显示您尝试与之交互的示例?如果需要,请随时更改内容。

标签: python pandas dataframe


【解决方案1】:

根据我对问题陈述的理解遵循我的解决方案:

import pandas as pd

#Creating Data Frames
df1 = pd.DataFrame({'testname':['88test', 'nonono', '88test'],
               'col2': [1, 2, 3],
               'col3': [4, 5, 6]})
df2 = pd.DataFrame({'88test':[9, 10], 'col4':[11, 12]})

#Selecting rows and column of interest from df1
df1_selected_rows = df1[['testname']][df1['testname']=='88test']
df1_selected_rows.rename(columns={'testname':'88test'}, inplace=True)

#Merging data of interest into df2 using pandas.merge()
pd.merge(df2, df1_selected_rows, how='outer')

#The same can be achieved using pandas.concat(), but preserving the original indexes of both dataframes
pd.concat(objs=[df2,df1_selected_rows], sort=False)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    相关资源
    最近更新 更多