【问题标题】:Create a new column if one dataframe's row value is in another data frame's column and get that index如果一个数据框行值在另一个数据框的列中,则创建一个新列并获取该索引
【发布时间】:2019-02-13 02:02:53
【问题描述】:

我可能使这个问题过于复杂,但我似乎找不到简单的解决方案。

我有两个 DataFrame。我们称它们为 df1 和 df2。为了保持简单。假设 df1 有一列称为“某些数据”,而 df2 有两列称为“某些数据”和“其他数据”。

例子:

df1

Some Data "Lebron James 123" "Lebron James 234"

df2

some data                        other data
"Lebron James 123 + other text"  "I want this in df1["New?"]"
"Michael Jordan"                 "Doesn't Matter"

所以基本上我想在 df1 中创建一个名为“New?”的新列。如果 df1["Some data"] 在 df2["Some other data"] 中,这个新列(在 df1 中)将显示“New”。但是,如果 df2["some data"] 中没有实例,那么我将 df1["New?"] 设置为 df2["other data"] 中该特定行的值。

运行后想要的结果:

df1

Some Data                         New?
"Lebron James 123"  "I want this in df1["New?"]"
"Lebron James 234"               "New"

所以你可以看到The New?列将包括来自其他数据列的特定行的值。 Lebron James 234 在 df2 的某些数据中并不存在,所以它说是新的。

我可以使用.isin() 方法让它说出True 或False,但是不知道如何获取其他df 的索引并从其他数据列中获取值。

谢谢

编辑:

据我所知会起作用

df["New?"] = df1["Some Data"].isin(df2["some data"])

会渲染

df1[“新的?”]

True
False

所以我希望 True 成为“我希望 df1[“New?”] 中的这个,而 False 成为新的

【问题讨论】:

  • 如果df1 中的值出现在 df2 的多行中怎么办?
  • 这对我没有影响。我只关心 df2["some data"] 中是否存在 df1["Some Data"] 的实例。如果没有从 df2["other data"] 中获取该行的值
  • 好的,这样就更容易了...还有一个问题,你的df1呢?似乎你应该在第一行有+ other text,否则它不会在你的输出中产生True

标签: python pandas dataframe


【解决方案1】:

根据您的信息,您似乎只需要一个简单的np.where(如果dfs 具有相同的长度)

df1['New?'] = np.where(df1["Some Data"].isin(df2["some data"]), df2['other data'], 'New')

    Some Data                       New?
0   Lebron James 123 + other text   I want this in df1[New?"]"
1   Lebron James 234                New

对于不同的长度,

mask = df2["some data"].isin(df["Some Data"]).values
df.loc[mask,'New'] = df2.loc[mask, 'other data']

df.fillna('New')

解释

基本上你有一个掩码,你使用相同的掩码过滤两个数据帧。这会在给定描述的情况下在 dfs 上产生相同数量的结果,并将过滤行的“其他数据”值从 df2 分配给 df“一些数据”中的相同匹配行

【讨论】:

  • 感谢您的帮助。希望我能想到 np.where... 我尝试运行它并收到此错误:ValueError: operands could not be broadcast together with shapes (13294,) (2432,) ()
  • 另外,它如何知道从 df2["other data"] 中获取哪个行号?这就是我的困惑
  • 谢谢...这是一个很长的公式。你能准确解释一下在做什么吗?我在关注它时遇到了问题。
  • @BeastlyBernardo 不确定我是否清楚,但刚刚编辑过。 :)
  • 嗯......好吧,我猜该代码是有道理的,但没有产生我需要的结果。一切都得到了NaN。所以回到这个索引问题。我将如何获取匹配的 df2 的行号(索引),即当 df["Some Data"].isin(df2["some data"]) 为 True 时。所以我需要以某种方式对上述代码进行 df2.index ......这有意义吗?
【解决方案2】:

首先通过加入您的df1 系列来创建一个正则表达式:

rgx = '|'.join(df1['some data'])

现在使用np.where

df1.assign(data=np.where(df2['some data'].str.match(rgx), df2['other data'], 'New'))

          some data                        data
0  Lebron James 123  I want this in df1["New?"]
1  Lebron James 234                         New

形状不匹配的示例:

df1 = pd.DataFrame({'a': ['a', 'b', 'c', 'd']})
df2 = pd.DataFrame({'a': ['aaaaa', 'bbbb', 'ffff', 'gggg', 'hhhh']})

rgx = '({})'.format('|'.join(df1.a))
m = df2.assign(flag=df2.a.str.extract(rgx))

df1.set_index('a').join(m.set_index('flag')).fillna('New').reset_index()

  index      a
0     a  aaaaa
1     b   bbbb
2     c    New
3     d    New

【讨论】:

  • 与上述类似的解决方案,但我相信我会得到同样的错误。我使用的实际数据框的大小有很大不同(一个有 13924 行,另一个有大约 2432 行)。我要问的一个更简单的问题是如何获取 df2 的那一行的索引?
  • 类似,但是这个答案会进行部分字符串匹配,因此它会检查df1['some data'] 中的值是否是df2['some data'] 中的anywhere,而不是完全匹配。我会更新不同的形状
  • @BeastlyBernardo 添加了形状不匹配的解决方案
猜你喜欢
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多