【问题标题】:replace row values with row values from another column if conditions met如果满足条件,则将行值替换为另一列中的行值
【发布时间】:2018-10-23 10:23:21
【问题描述】:

我想替换 pandas 中的行值。

import pandas as pd
import numpy as np
data = {'type': ['place', 'home', 'place', 'walk', 'place', 'work', 'home', 'place'],'labels': ['NaN', 'NaN', 'shop', 'Nan', 'clinic', 'NaN', 'NaN', 'NaN']}
a = pd.DataFrame(data, columns = ['type', 'labels'])

如果 a['labels'] 不是 np.NaN 并且 a['type'] == 'place' 使用熊猫?

如果可能的话,我更喜欢使用 df.loc[]。

【问题讨论】:

    标签: python-3.x pandas dataframe data-manipulation


    【解决方案1】:

    首先,您提供的数据实际上不是np.NaN,它只是字符串'NaN''Nan',它们的处理方式不同。如果这是您的起点,您可以这样做:

    a['labels'] = a['labels'].str.lower().replace('nan', np.NaN)
    

    然后定义您的mask 并替换:

    mask = (a['labels'].notnull()) & (a['type'] == 'place') 
    df.loc[mask, 'type'] = df.loc[mask, 'labels']
    
         type  labels
    0   place     NaN
    1    home     NaN
    2    shop    shop
    3    walk     NaN
    4  clinic  clinic
    5    work     NaN
    6    home     NaN
    7   place     NaN
    

    或者,使用上面定义的相同mask,您可以使用numpy.where

    a['type'] = np.where(mask, a['labels'], a['type'])
    

    【讨论】:

    • 你是最棒的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2022-10-07
    • 2021-12-22
    • 1970-01-01
    • 2020-08-18
    • 2019-06-05
    • 1970-01-01
    相关资源
    最近更新 更多