擅长:python、mysql、java
<p>您可以使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer">^{<cd1>}</a>将月-年字符串(例如<code>JAN2021</code>)转换为日期时间格式。然后,使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer">^{<cd3>}</a>将datetime对象格式化为<code>mmm-YYYY</code>(例如<code>Jan-2021</code>)中所需的布局,如下所示:</p>
<p>(假设您的数据帧名为<code>df</code>,列名为<code>Col1</code>):</p>
<pre><code>df['Col_new'] = pd.to_datetime(df['Col1'], format='%b%Y').dt.strftime('%b-%Y')
</code></pre>
<p>结果:</p>
<pre><code>print(df)
Col1 Col_new
0 JAN2021 Jan-2021
1 FEB2021 Feb-2021
2 MAR2021 Mar-2021
3 APR2021 Apr-2021
</code></pre>
<p>您在试用代码中使用了无效的格式字符串<code>"%mmm%YY"</code>。有关有效格式字符串及其含义的完整列表,以及示例,您可以参考Python官方文档<a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes" rel="nofollow noreferrer">here</a></p>