【问题标题】:Create pandas data frame column based on strings from two other columns根据来自其他两列的字符串创建熊猫数据框列
【发布时间】:2018-07-25 09:42:18
【问题描述】:

我有一个如下所示的数据框:

boat_type   boat_type_2
Not Known   Not Known
Not Known   kayak
ship        Not Known
Not Known   Not Known
ship        Not Known

我想创建第三列boat_type_final,应该如下所示:

boat_type   boat_type_2  boat_type_final
Not Known   Not Known    cruise
Not Known   kayak        kayak
ship        Not Known    ship  
Not Known   Not Known    cruise
ship        Not Known    ship

所以基本上如果boat_typeboat_type_2 中都存在“未知”,那么该值应该是“巡航”。但如果前两列中存在“Not Known”以外的字符串,则应使用该字符串填充boat_type_final,“kayak”或“ship”。

最优雅的方法是什么?我见过几个选项,例如where、创建函数和/或逻辑,我想知道真正的 pythonista 会做什么。

到目前为止,这是我的代码:

import pandas as pd
import numpy as np
data = [{'boat_type': 'Not Known', 'boat_type_2': 'Not Known'},
    {'boat_type': 'Not Known',  'boat_type_2': 'kayak'},
    {'boat_type': 'ship',  'boat_type_2': 'Not Known'},
    {'boat_type': 'Not Known',  'boat_type_2': 'Not Known'},
    {'boat_type': 'ship',  'boat_type_2': 'Not Known'}]
df = pd.DataFrame(data
df['phone_type_final'] = np.where(df.phone_type.str.contains('Not'))...

【问题讨论】:

    标签: python python-3.x pandas numpy dataframe


    【解决方案1】:

    用途:

    df['boat_type_final'] = (df.replace('Not Known',np.nan)
                               .ffill(axis=1)
                               .iloc[:, -1]
                               .fillna('cruise'))
    print (df)
       boat_type boat_type_2 boat_type_final
    0  Not Known   Not Known          cruise
    1  Not Known       kayak           kayak
    2       ship   Not Known            ship
    3  Not Known   Not Known          cruise
    4       ship   Not Known            ship
    

    解释

    首先replaceNot Known 到缺失值:

    print (df.replace('Not Known',np.nan))
      boat_type boat_type_2
    0       NaN         NaN
    1       NaN       kayak
    2      ship         NaN
    3       NaN         NaN
    4      ship         NaN
    

    然后通过每行前向填充替换NaNs:

    print (df.replace('Not Known',np.nan).ffill(axis=1))
      boat_type boat_type_2
    0       NaN         NaN
    1       NaN       kayak
    2      ship        ship
    3       NaN         NaN
    4      ship        ship
    

    iloc的位置选择最后一列:

    print (df.replace('Not Known',np.nan).ffill(axis=1).iloc[:, -1])
    0      NaN
    1    kayak
    2     ship
    3      NaN
    4     ship
    Name: boat_type_2, dtype: object
    

    如果可能的话NaNs 添加fillna:

    print (df.replace('Not Known',np.nan).ffill(axis=1).iloc[:, -1].fillna('cruise'))
    0    cruise
    1     kayak
    2      ship
    3    cruise
    4      ship
    Name: boat_type_2, dtype: object
    

    如果只有几列的另一种解决方案是使用numpy.select

    m1 = df['boat_type'] == 'ship'
    m2 = df['boat_type_2'] == 'kayak'
    
    df['boat_type_final'] = np.select([m1, m2], ['ship','kayak'], default='cruise')
    print (df)
       boat_type boat_type_2 boat_type_final
    0  Not Known   Not Known          cruise
    1  Not Known       kayak           kayak
    2       ship   Not Known            ship
    3  Not Known   Not Known          cruise
    4       ship   Not Known            ship
    

    【讨论】:

    • 你能解释一下它是如何/为什么起作用的吗?特别是这部分:.ffill(axis=1).iloc[:, -1]
    • @bzier - 当然,等一下。
    • @bzier - 答案已修改。
    【解决方案2】:

    另一种解决方案是在您拥有映射的地方定义您的函数:

    def my_func(row):
        if row['boat_type']!='Not Known':
            return row['boat_type']
        elif row['boat_type_2']!='Not Known':
            return row['boat_type_2']
        else: 
            return 'cruise'
    

    [注意:您没有提到当两列都不是“未知”时应该发生什么。]

    然后简单地应用函数:

    df.loc[:,'boat_type_final'] = df.apply(my_func, axis=1)
    
    print(df)
    

    输出:

       boat_type boat_type_2 boat_type_final
    0  Not Known   Not Known          cruise
    1  Not Known       kayak           kayak
    2       ship   Not Known            ship
    3  Not Known   Not Known          cruise
    4       ship   Not Known            ship
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 2023-01-12
      • 2019-12-09
      • 2022-07-07
      • 2019-07-25
      • 2020-10-21
      相关资源
      最近更新 更多