1. 程式人生 > >pandas.DataFrame 根據條件新建列並賦值

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)