python pandas 'AttributeError: Can only use .dt accessor with datetimelike values' decimal to hours
<p>I have a column in a df that looks like </p>

<pre><code>hour
1.0
2.0
3.0
6.0 
Nan
</code></pre>

<p>I want to convert this into a time format so like below</p>

<pre><code>hour
1:00
2:00
3:00
6:00
</code></pre>

<p>However I cannot get the formatting correct. I have tried to coerce the format like below. I would also like the logic to leave the Nan values.</p>

<pre><code>pd.to_datetime(df['hour'], format='%H', coerce=True)
</code></pre>

<p>But this only returns NaT values.</p>

<p>Here:</p>

<pre><code>pd.to_datetime(df['hour'], unit='h')
</code></pre>

<p>Change the <code>format</code> to <code>unit</code>. If you are using numeric data (like you are), then you <strong>cannot</strong> use <code>format</code>. <code>format</code> works only on strings.</p>

<p><code>%H</code>, for example is string interpolation, and since your data is numeric (float), string interpolation will fail.</p>

<hr>

<p>Note that the printed output will not resemble the output in the question. Because, pandas will convert it to datetime type. It will look like <code>'1970-01-01 00:00:00'</code> when printed. If you want the desired format, you can run either:</p>

<pre><code>pd.to_datetime(df['hour'], unit='h').apply(lambda h: '{}:00'.format(h.hour))
</code></pre>

<p>Or:</p>

<pre><code>df['hour'].apply(lambda h: '{}:00'.format(h))
</code></pre>

python pandas