一康嘉、讀取數(shù)據(jù)
數(shù)據(jù)內(nèi)容如下:
ymd,bwendu,ywendu,tianqi,fengxiang,fengli,aqi,aqiinfo,aqiLevel
2018-01-01,3C,-6C,多云,東北風(fēng),1-2級,59,良,2
2018-01-02,4C,-6C,多云,東北風(fēng),3-4級,60,良,2
2018-01-03,5C,-6C,多云,東北風(fēng),5-6級,61,良,2
df = pd.read_csv(data_path)
image.png
二、直接賦值新增列
df.loc[:,'bwendu'] = df['bwendu'].str.replace('C','').astype('int32')
df.loc[:,'ywendu'] = df['ywendu'].str.replace('C','').astype('int32')
image.png
df['wencha2'] = df['bwendu'] - df['ywendu']
image.png
三籽前、使用apply傳入函數(shù)新增列
def get_wendu_type(x):
if x['bwendu'] >=4:
return 'high temp'
if x['ywendu'] <=-6:
return 'low temp'
return 'normal temp'
df['wendu_type'] = df.apply(get_wendu_type, axis=1)
image.png
四亭珍、使用assign同時新增多列
df.assign(
ywendu_huashi = lambda x:x['ywendu'] * 9 + 2,
bwendu_huashi = lambda x:x['bwendu'] * 9 + 2
)
image.png
五、按條件新增列
df['wencha_type2'] = '溫差正常'
df.loc[df['bwendu']-df['ywendu']>=11, 'wencha_type2'] = '溫差大'
df.loc[df['bwendu']-df['ywendu']<=9, 'wencha_type2'] = '溫差小'
image.png
六枝哄、統(tǒng)計列中元素的個數(shù)
df['wencha_type2'].value_counts()
image.png