Я думаю, вы путаете, как хранится информация (dtype) и как она отображается для вас.Пример кода ниже иллюстрирует это:
import pandas as pd
# create sample dataframe where month is a string
df = pd.DataFrame({'month_str':['1949-01', '1949-02', '1949-03']})
# now create a new column where you have converted the string to a datetime
df['month_datetime'] = pd.to_datetime(df['month_str'])
# now convert the datetime back to a string with your desired format
df['month_new_str'] = df['month_datetime'].dt.strftime('%Y/%m')
# skip all the fooling around with datetimes and just manipulate it as a string directly
df['month_new_str2'] = df['month_str'].apply(lambda x: x.replace('-', '/'))
print(df.dtypes)
print(df)
Это приводит к следующему выводу:
month_str object
month_datetime datetime64[ns]
month_new_str object
month_new_str2 object
dtype: object
month_str month_datetime month_new_str month_new_str2
0 1949-01 1949-01-01 1949/01 1949/01
1 1949-02 1949-02-01 1949/02 1949/02
2 1949-03 1949-03-01 1949/03 1949/03
Обратите внимание, что исходный столбец 'month_str' имеет объект типа d (это строка),Когда вы вызывали to_datetime, мы конвертировали его в тип datetime (указывать формат не нужно, панды это выясняют).Но когда он отображается, pandas отображает его как полную дату (вот почему вы видите поле дня).Как указывает @sds, если вы просто хотите отключить тире для косой черты, вы можете просто манипулировать исходной строкой, чтобы создать новую строку ('month_new_str2').