【问题标题】:replace an item of a column based on another column基于另一列替换一列的项目
【发布时间】:2021-07-31 01:33:16
【问题描述】:

我正在尝试根据另一列的数据替换一列的一项,如下代码:

import pandas as pd
import numpy as np
data = np.array([['3S', 12345],['-2', 12345], ['4S', 12334], ['-2', 12334]])
df = pd.DataFrame(data, columns=['col_1', 'col_2'])
df

#I'd like to find the item "-2" at col_1 and replace it based on the data of the col_2. As result, i'd like to have a dataframe like this:

data = np.array([['3S', 12345],['3S', 12345], ['4S', 12334], ['4S', 12334]])
df = pd.DataFrame(data, columns=['col_1', 'col_2'])
df

【问题讨论】:

    标签: python pandas dataframe numpy


    【解决方案1】:

    让我们试试

    df.col_1 = df.col_1.mask(df.col_1.isin(['-2'])).\
                  groupby(df['col_2']).transform('first')
    df
    Out[50]: 
      col_1  col_2
    0    3S  12345
    1    3S  12345
    2    4S  12334
    3    4S  12334
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-18
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      相关资源
      最近更新 更多