为什么我的可以运行的代码在添加%timeit后直接运行失败并提示ValueError?

Why does my code that can be run directly fail to run after adding %timeit and prompt ValueError?

我的代码可以运行直接without加上%timeit:

df = pd.DataFrame(np.arange(1, 13), columns=['month'])
df['month']=df['month'].apply('{:02}'.format)

但是在adding%timeit之后我不能运行,提示ValueError。这是为什么?

df = pd.DataFrame(np.arange(1, 13), columns=['month'])
%timeit df['month']=df['month'].apply('{:02}'.format)
ValueError: '=' alignment not allowed in string format specifier

我去掉df['month']=后,可以运行.

%timeit df['month'].apply('{:02}'.format)
395 µs ± 5.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit 通过 运行 多次运行您的程序并评估每次迭代需要多长时间来工作。在第一个示例中,更新了 DataFrame。请注意,如果 运行 以下内容,您也会收到此错误:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.arange(1, 13), columns=['month'])
# month column is all numbers
df['month'] = df['month'].apply('{:02}'.format)

# month column is now all strings not numbers anymore
df['month'] = df['month'].apply('{:02}'.format)
ValueError: '=' alignment not allowed in string format specifier

更简单的是你会得到这个错误运行宁这个代码('01'是第二行中第一行的值运行):

'{:02}'.format('01')
ValueError: '=' alignment not allowed in string format specifier

不赋值的原因自然是 DataFrame 没有更新,因此你总是从一个数值开始,可以 与该格式字符串一起使用。

import numpy as np
import pandas as pd

df = pd.DataFrame(np.arange(1, 13), columns=['month'])
# These do not affect the values in DF
df['month'].apply('{:02}'.format)
df['month'].apply('{:02}'.format)
df['month'].apply('{:02}'.format)
df['month'].apply('{:02}'.format)
# Exactly the same as the constructor
print(df)

从 Python 的 Format Specification Mini-Language 我们可以看到这个错误通知我们无法为字符串值设置填充:

Option Meaning
'=' Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width.