Dataframe通过在另一个Dataframe中查找另一个列的出现来填充一列的值。

huangapple go评论70阅读模式
英文:

Dataframe fill up a column values by finding the occurence of an other one in an other Dataframe

问题

如您可能已经理解的,我的问题非常具体...
所以我有两个数据框,其中一个列可以被视为“中心”列。
这个中心列的所有值都是唯一的。
我们的目标是向第一个数据框添加一个新列,其中包含第二个数据框中某一列的值。

这是我目前尝试的内容,不幸的是它没有成功 :/

df1['NewColumn'] = '0'  #我创建了第一列并设置了默认值

df1.loc[df2['PivotCol'] == df1['PivotCol'], 'NewColumn'] = df2.loc[df2['PivotCol'] == df1['PivotCol'], 'ColumnToMergeTo1stDataframe'].iloc[0]

NewColumn是在df1中新创建的列,它将包含df2中的ColumnToMergeTo1stDataframe的值...

我希望我的问题清楚,如果不清楚,请随时提问。

最后但并非最不重要,对于糟糕的英语,我表示抱歉 Dataframe通过在另一个Dataframe中查找另一个列的出现来填充一列的值。

英文:

As you may have understood, my question is quite specific...
So I have 2 dataframes with a column which could be seen as a "Pivot" column.
All the values of this Pivot column are unique.
Our goal is to add a new column to the first Dataframe containing the value of a column in the second one.

This is what I tried for now, it unfortunately didn't work :/

df1['NewColumn] = '0'  //I created the first column and set a default value

df1.loc[df2['PivotCol'] == df1['PivotCol'], 'NewColumn'] = df2.loc[df2['PivotCol'] == df['PivotCol'], 'ColumnToMergeTo1stDataframe'].iloc[0]

NewColumn is the newly created column in df1 which will be containing the value of ColumnToMergeTo1stDataframe which is in the df2...

I hope that my problem is clear, don't hesitate to ask questions if it was not.

Last but not least, sorry for bad english Dataframe通过在另一个Dataframe中查找另一个列的出现来填充一列的值。

答案1

得分: 0

A panda merge made the job :)
英文:
df = pd.merge(df1, df2[['Col Pivot', 'Col to Merge']], on='Col Pivot', how='left')

A panda merge made the job Dataframe通过在另一个Dataframe中查找另一个列的出现来填充一列的值。

huangapple
  • 本文由 发表于 2020年1月6日 18:34:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定