簡體   English   中英

我有兩個數據框。 我想將一個數據框的標題與另一數據框的一列的內容進行比較

[英]I have two dataframes. I wanted to compare header of one dataframe with the content of one column in another dataframe

我有兩個數據框。 在第一個數據幀中,有一個列名testname,其中我有88個測試,在第二個數據幀中,我將那些測試名作為標題。 因此,現在我想將第一個數據幀中的testname列的內容與第二個數據幀的標頭進行比較。 我想檢查第一個數據框中的每個id是否可以使用testname,我想在第二個數據框中添加特定的testname值。

我已經通過迭代兩個數據幀來進行嘗試,並且第一步也完成了匹配ID的操作,但是我不知道如何同時比較內容和標頭

根據我對問題陳述的理解,遵循我的解決方案:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM