我有两个看起来像这样的df:
sed
如何合并这两个数据框,并且如果匹配则仅从新列中的df1:
id
1
2
df2:
id value
2 a
3 b
列返回数据?
value
答案 0 :(得分:2)
您可以使用@ JJFord3设置进行尝试:
import pandas
df1 = pandas.DataFrame(index=[1,2])
df2 = pandas.DataFrame({'value' : ['a','b']},index=[2,3])
#Use isin to create new_value
df2['new_value'] = df2['value'].where(df2.index.isin(df1.index))
#Use reindex with union to rebuild dataframe with both indexes
df2.reindex(df1.index.union(df2.index))
输出:
value new_value
1 NaN NaN
2 a a
3 b NaN
答案 1 :(得分:1)
import pandas
df1 = pandas.DataFrame(index=[1,2])
df2 = pandas.DataFrame({'value' : ['a','b']},index=[2,3])
new_merged_df_outer = df1.merge(df2,how='outer',left_index=True,right_index=True)
new_merged_df_inner = df1.merge(df2,how='inner',left_index=True,right_index=True)
new_merged_df_inner.rename(columns={'value':'new_value'})
new_merged_df = new_merged_df_outer.merge(new_merged_df_inner,how='left',left_index=True,right_index=True)
首先,创建一个外部合并以保留所有索引。 然后创建一个内部合并仅获得重叠。 然后将内部合并合并回外部合并,以获取所需的列设置。
答案 2 :(得分:0)
df = df1.merge(df2,on='id',how='outer')
id_value = df2.loc[df2['id'].isin(df1.id.tolist()),'id'].unique()
mask = df['id'].isin(id_value)
df.loc[mask,'new_value'] = df.loc[mask,'value']
# alternative df['new_value'] = np.where(mask, df['value'], np.nan)
print(df)
id value new_value
0 1 NaN NaN
1 2 a a
2 3 b NaN
答案 3 :(得分:0)
您可以使用full outer join
让我们使用案例类对数据建模:
case class MyClass1(id: String)
case class MyClass2(id: String, value: String)
// this one for the result type
case class MyClass3(id: String, value: Option[String] = None, value2: Option[String] = None)
创建一些输入:
val input1: Dataset[MyClass1] = ...
val input2: Dataset[MyClass2] = ...
加入数据:
import scala.implicits._
val joined = input1.as("1").joinWith(input2.as("2"), $"1.id" === $"2.id", "full_outer")
joined map {
case (left, null) if left != null => MyClass3(left.id)
case (null, right) if right != null => MyClass3(right.id, Some(right.value))
case (left, right) => MyClass3(left.id, Some(right.value), Some(right.value))
}
答案 4 :(得分:0)
DataFrame.merge
在参数indicator
中具有
如果为True,则在输出数据帧中添加一列,称为“ _merge”,其中包含有关每一行源的信息。
这可用于检查是否存在匹配项
import pandas as pd
df1 = pd.DataFrame(index=[1,2])
df2 = pd.DataFrame({'value' : ['a','b']},index=[2,3])
# creates a new column `_merge` with values `right_only`, `left_only` or `both`
merged = df1.merge(df2, how='outer', right_index=True, left_index=True, indicator=True)
merged['new_value'] = merged.loc[(merged['_merge'] == 'both'), 'value']
merged = merged.drop('_merge', axis=1)