One - One Code All

Blog Content

pandas.DataFrame根据条件新建列并赋值

Python 统计学-科学计算   2014-06-07 21:01:37

pandas  DataFrame 新建列赋值

import numpy as np
import pandas as pd
 
data = {'city': ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen', 'Hangzhou', 'Chongqing'],
       'year': [2016,2016,2015,2017,2016, 2016],
       'population': [2100, 2300, 1000, 700, 500, 500]}
frame = pd.DataFrame(data, columns = ['year', 'city', 'population', 'debt'])
 
# 使用apply函数, 如果city字段包含'ing'关键词,则'判断'这一列赋值为1,否则为0
frame['panduan'] = frame.city.apply(lambda x: 1 if 'ing' in x else 0)
print(frame)



上一篇:pandas中DataFrame的连接操作join
下一篇:pandas中dataframe的合并append, merge, concat

The minute you think of giving up, think of the reason why you held on so long.