【问题标题】:How to create a new column in a Pandas DataFrame based on a column in another DataFrame?如何基于另一个 DataFrame 中的列在 Pandas DataFrame 中创建新列?
【发布时间】:2019-02-16 01:15:45
【问题描述】:

*我是 Python 和 Pandas 的新手
我需要执行以下操作
我有 2 个 DataFrame,我们称它们为 df1 和 df2

df1

Index    Req ID  City_Atlanta   City_Seattle    City_Boston Result  
 0        X         1                0            0           0  
 1        Y         0                1            0           0  
 2        Z         0                0            1           1

df2

Index    Req_ID    City        
  0         X      Atlanta     
  1         Y      Seattle     
  2         Z      Boston    

我想在 df2 中添加一个名为 result 的列,如果 df1.result = 0 则 df2.result = False,如果 df1.result = 1 则 df2.result = True

最终结果应该是这样的 df2

Index    Req_ID    City       result 
  0         X      Atlanta     False
  1         Y      Seattle     False
  2         Z      Boston      True

我对 Stack Overflow 也很陌生,所以请原谅任何常见的错误。

【问题讨论】:

  • 基于什么? 2个数据帧之间的共同键是什么?你能解释一下吗?
  • 索引或 Req_ID

标签: python pandas dataframe


【解决方案1】:

考虑到Req ID是匹配的key和dfs的长度不一样,可以使用:

df2['Result'] = df2.Req_ID.map(dict(zip(df['Req ID'],df.Result))).astype(bool)

0    False
1    False
2     True

如果长度相等,您可以使用@aws_apprentice 提供的上述 sol

【讨论】:

    【解决方案2】:

    你可以applybool 到 0,1's。

    df2['Result'] = df1['Result'].apply(bool)
    

    您还可以map 值字典。

    df2['Result'] = df1['Result'].map({0: False, 1: True})
    

    【讨论】:

    • 是的,OP还没有指定任何东西
    • 更改适用于 astype
    • 这是另一种可能的解决方案
    【解决方案3】:

    假设它们的长度相同:

    df2['Result'] = df1['Result']==1
    

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 2016-05-26
      • 1970-01-01
      相关资源
      最近更新 更多