我认为您可以使用
numpy.where:
import pandas as pdimport numpy as npdf = pd.Dataframe(np.random.randint(0,9,size=(100, 1)), columns=['number'])df['odd_or_even'] = np.where(df.number % 2, 'odd', 'even')print (df) number odd_or_even0 1 odd1 0 even2 4 even3 5 odd4 0 even5 0 even6 1 odd7 0 even8 7 odd9 8 even
通过评论编辑
loc:
import pandas as pdimport numpy as npdf = pd.Dataframe(np.random.randint(0,9,size=(20, 1)), columns=['number'])odd_numbers = [1,3,5,7,9]even_numbers = [0,2,4,6,8]df.loc[df.number.isin(odd_numbers), 'odd_or_even'] = 'odd'df.loc[df.number.isin(even_numbers), 'odd_or_even'] = 'even'print (df) number odd_or_even0 5 odd1 1 odd2 2 even3 3 odd4 5 odd5 6 even6 3 odd7 4 even8 2 even9 8 even10 8 even11 1 odd12 2 even13 1 odd14 3 odd15 3 odd16 5 odd17 4 even18 2 even19 5 odd
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)