Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

有一excel文件,有上千条数据,需要根据“地点”这一列,如果为北京,在“类型”这列写入‘A’,为上海,在“类型”这列写入‘B’,为广州,在“类型”这列写入‘C’,如果不用excel公式用pandas怎样实现?

序号 日期 地点 金额 类型
1 2020/04/09 北京 100.00
2 2020/04/10 上海 90.00
3 2020/04/10 广州 80.00

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
469 views
Welcome To Ask or Share your Answers For Others

1 Answer

numpy.where 可以。

In [1]: import pandas as pd     

In [2]: import numpy as np                                   

In [3]: df = pd.DataFrame({'city': ['北京', '上海', '广州']})                 

In [4]: df['t'] = np.where(df.city == '北京', 'A', np.where(df.city == '上海', 'B', np.where(df.city == '广州', 'C', '?')))               

In [5]: df                                                                                                                                
Out[5]: 
  city  t
0   北京  A
1   上海  B
2   广州  C

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...