Trying to merge 2 dataframes but get ValueError

前端 未结 7 1155
别那么骄傲
别那么骄傲 2020-11-30 04:15

These are my two dataframes saved in two variables:

> print(df.head())
>
          club_name  tr_jan  tr_dec  year
    0  ADO Den Haag    1368    1422          


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 05:11

    @Arnon Rotem-Gal-Oz answer is right for the most part. But I would like to point out the difference between df['year']=df['year'].astype(int) and df.year.astype(int). df.year.astype(int) returns a view of the dataframe and doesn't not explicitly change the type, atleast in pandas 0.24.2. df['year']=df['year'].astype(int) explicitly change the type because it's an assignment. I would argue that this is the safest way to permanently change the dtype of a column.

    Example:

    df = pd.DataFrame({'Weed': ['green crack', 'northern lights', 'girl scout cookies'], 'Qty':[10,15,3]}) df.dtypes

    Weed object, Qty int64

    df['Qty'].astype(str) df.dtypes

    Weed object, Qty int64

    Even setting the inplace arg to True doesn't help at times. I don't know why this happens though. In most cases inplace=True equals an explicit assignment.

    df['Qty'].astype(str, inplace = True) df.dtypes

    Weed object, Qty int64

    Now the assignment,

    df['Qty'] = df['Qty'].astype(str) df.dtypes

    Weed object, Qty object

提交回复
热议问题