【问题标题】:Pandas df: fill values in new column with specific values from another column (condition with multiple columns)Pandas df:用另一列的特定值填充新列中的值(具有多列的条件)
【发布时间】:2022-01-05 07:26:36
【问题描述】:

我有一个数据框:

df = pd.DataFrame({'col1': ['a', 'b', 'c', 'd'], 'col2': ['b', 'c', 'd', 'e'], 'col3': [1.0, 2.0, 3.0, 4.0]})

  col1 col2  col3
0    a    b   1.0
1    b    c   2.0
2    c    d   3.0
3    d    e   4.0

我的目标是创建一个额外的 col4,其中包含来自 col3 的特定值和条件:对于每一行 x,查看 col1 中的值,如果在 df 中的任何位置存在另一行 y,该值存在于 col2 ,从这行 y 中取出 col3 值,并将其作为 col4 放入原始行 x 中。否则,将此行的 col4 留空,例如南。

所以 col4 的预期输出是:NaN, 1, 2, 3。对于第一行没有值,因为数据框中没有“a”为 col2 的行。 与此示例不同,行可以在 df 中完全未排序!

Expected output:

  col1 col2  col3  col4
0    a    b   1.0   NaN
1    b    c   2.0   1.0
2    c    d   3.0   2.0
3    d    e   4.0   3.0

我尝试过使用 .mask,但到目前为止没有运气。感谢您的帮助!

【问题讨论】:

  • 您能否提供一个示例预期输出数据框来帮助我了解需求?
  • 我将其编辑到问题中。
  • 我注意到在 dtype int 的列中 NaN 是不可能的,所以我将 col3 更改为 float。

标签: python pandas dataframe


【解决方案1】:

您可以使用左侧的 col1 和右侧的 col2 将数据框连接到自身。

将连接右侧的 col3 重命名为 col4 并删除其余的右侧列 示例:

df = df.merge(df, left_on='col1', right_on='col2', how='left', suffixes=('', '_'))
df = df.rename(columns={'col3_': 'col4'})
df = df[['col1', 'col2', 'col3', 'col4']]

df 看起来像:

  col1 col2  col3  col4
0    a    b     1   NaN
1    b    c     2   1.0
2    c    d     3   2.0
3    d    e     4   3.0

【讨论】:

    猜你喜欢
    • 2017-06-22
    • 2020-12-29
    • 2020-11-17
    • 2021-04-27
    • 1970-01-01
    • 2020-09-03
    • 2020-09-16
    • 2019-12-09
    • 2021-03-18
    相关资源
    最近更新 更多