如何使用其他列的条件添加列

2024-04-20 07:59:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧。你知道吗

df=pd.DataFrame({'month':np.arange(1,8)})

所以,我想通过使用'month'列来添加列

if 'month'=1,2,3   the elements = 'term1'
   'month'=4,5     the elements = 'term2' 
   'month'=6,7     the elements = 'term3'

我想得到下面的结果

      month  term 
0       1    term1
1       2    term1
2       3    term1
3       4    term2
4       5    term2
5       6    term3
6       7    term3

我怎样才能得到这个结果? 也许我们可以用简单的方法得到这个结果。。。。你知道吗


Tags: the数据term1方法dataframedfifnp
2条回答

使用numpy.whereSeries.isin()方法可以是执行此操作的选项之一:

import numpy as np
import pandas as pd
df["term"] = np.where(df.month.isin([1,2,3]), "term1", \
                      np.where(df.month.isin([4,5]), "term2", "term3"))

df
# month  term
#0    1 term1
#1    2 term1
#2    3 term1
#3    4 term2
#4    5 term2
#5    6 term3
#6    7 term3

我会选择一种声明性的方式,通过口述,简单易读,易于应用。如果替换条件变大或依赖于其他输入,则可以通过编程方式生成替换条件字典:

conditions = {1:'term1', 2:'term1', 3:'term1',
              4:'term2', 5:'term2',
              6:'term3', 7:'term3'}

df['term'] = df.replace(conditions)
df

      month  term 
0       1    term1
1       2    term1
2       3    term1
3       4    term2
4       5    term2
5       6    term3
6       7    term3

相关问题 更多 >