【问题标题】:Combine 2 string columns in pandas with different conditions in both columns with another condition within将 pandas 中的 2 个字符串列与两列中的不同条件与另一个条件相结合
【发布时间】:2022-01-22 06:53:32
【问题描述】:

我有以下数据框,除了cat1之外还有其他类别,但我只想更改类别为cat1的数据框部分。

name   short code     category
thyrax thx   thxar.po cat1
gha    gh    gh.cd    cat1
play   pl    pl.v     cat1
xxdx   xd    xda.v    cat1
......

如果代码列中. 之后的所有内容都是.cd 之外的任何内容,我希望短列采用短列中的内容+code 列中. 之后的内容和变成thx.po,但如果有cd,我希望它变成.cn。我希望输出看起来像这样,

name   short    code     category
thyrax thx.po   thxar.po cat1
gha    gh.cn    gh.cd    cat1
play   pl.v     pl.v     cat1
xxdx   xd.v     xda.v    cat1
......

不知道怎么加一个条件IF的类别是cat1.后面的代码是.cd,变成short+.后面的代码+ cn.

我希望对所有内容都使用相同的条件,除非要复制 . 之后的内容,但如果 . 之后的内容是 .cn,我希望它是 .cd。最好的方法是什么?

到目前为止,我已经得到了这个代码,

df['short'] = (df['short'].add("."+df['code'].str.split(".").str[-1]).where(df['category'].eq("cat1"),df['short']))

但我不知道如何添加条件,如果在代码列中,. 之后出现的是.cd 并发生不同的事情。

所以基本上我的条件是这样的,

首先,类别必须是cat1

然后将短列中的内容与代码列中.之后的内容合并。

如果代码栏中.后面是cd,则改为cn

【问题讨论】:

  • 您是否考虑过将 apply 与自定义函数一起使用,并将所有条件逻辑放在那里?
  • 不,我不知道该怎么做,你能指出我正确的方向吗

标签: python pandas if-statement conditional-statements


【解决方案1】:

试试这个:

df['short'] = df['short'].astype(str) + np.where(df['category'].eq('cat1'), df['code'].astype(str).str.extract('(\..+)')[0].replace('.cd', '.cn'), '')

输出:

>>> df
     name   short      code category
0  thyrax  thx.po  thxar.po     cat1
1     gha      gh     gh.cd     cat2
2     gha   gh.cn     gh.cd     cat1
3    play    pl.v      pl.v     cat1
4    xxdx      xd     xda.v     cat2
5    xxdx      xd     xda.v     cat2
6    xxdx    xd.v     xda.v     cat1

(我在上述数据中添加了一些虚拟行以证明它适用于正确的类别,cat1。)

【讨论】:

    【解决方案2】:

    试试:

    mask = df['category'] == 'cat1'
    df.loc[mask, 'short'] += '.' + df.loc[mask, 'code'] \
                                     .str.split('.').str[1].replace({'cd': 'cn'})
    print(df)
    
    # Output:
         name   short      code category
    0  thyrax  thx.po  thxar.po     cat1
    1     gha   gh.cd     gh.cd     cat1
    2    play    pl.v      pl.v     cat1
    3    xxdx    xd.v     xda.v     cat1
    

    【讨论】:

    • .后面是cd的情况怎么办,这种情况需要转换成.cn
    【解决方案3】:
    def custom_apply_function(row):
        if row['category'] != 'cat1':
            return row.short
        code_after_dot = row.code.split('.')[1]
        if code_after_dot == 'cd':
            code_after_dot = 'cn'
        new_short = row.short + '.' + code_after_dot
        return new_short
    
    df.apply(axis=1, func=custom_apply_function)
    

    返回

    0    thx.po
    1     gh.cn
    2      pl.v
    3      xd.v
    

    由于矢量化,此线程中的其他答案肯定更快。如果您想进一步复杂化条件,我会选择更明确的版本。

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 2019-06-17
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      相关资源
      最近更新 更多