Home >Backend Development >Python Tutorial >pandas.DataFrame method to create new columns and assign values based on conditions
Let me share with you a pandas.DataFrame method of creating new columns and assigning values based on conditions. It has certain reference value and I hope it will be helpful to everyone.
The example is as follows:
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)
Related recommendations:
Basic operation method of Python data analysis library pandas_python
Python solves the problem of pandas processing missing values as empty strings_python
##
The above is the detailed content of pandas.DataFrame method to create new columns and assign values based on conditions. For more information, please follow other related articles on the PHP Chinese website!