Pandas怎样新增数据列

    科技2024-03-10  88

    fpath = "datas/beijing_tianqi/beijing_tianqi_2018.csv" df = pd.read_csv(fpath) # print(df.head()) df.loc[:,"bWendu"] = df["bWendu"].str.replace("℃","").astype('int32') df.loc[:,"yWendu"] = df["yWendu"].str.replace("℃","").astype('int32') # 1 # 新增wencha df.loc[:,"wencha"] = df["bWendu"] - df["yWendu"] print(df.head()) # 2 apply def get_wendu_type(x): if x["bWendu"] > 33: return '高温' if x["yWendu"] < -10: return '低温' return '常温' df.loc[:,"wendu_type"] = df.apply(get_wendu_type,axis=1) print(df["wendu_type"].value_counts()) print(df.head()) #3 assign print(df.assign( yWendu_huashi=lambda x: x["yWendu"] * 9 / 5 + 32, bWendu_huashi=lambda x: x["bWendu"] * 9 / 5 + 32 )) # print(df['bWendu_huashi']) #这样会报错,因为df中并没有这个column # 3先创建空列(这是第一种创新列的方法) df['wencha_type'] = '' df.loc[df["bWendu"]-df["yWendu"]>10,"wencha_type"] = '温差大' df.loc[df["bWendu"]-df["yWendu"]<=10,"wencha_type"] = '温差正常' print(df["wencha_type"].value_counts())
    Processed: 0.019, SQL: 10