設置
df = pd.DataFrame(dict(
A='XX YY ZZ AA'.split(),
Date=pd.date_range('2017-03-31', periods=4)
))
選項1
apply
與lambda
基於format
和字典拆包。
這是一個緩慢但很酷的方式來做到這一點。
df.assign(C=df.apply(lambda x: '{Date:%Y-%m-%d}_{A}'.format(**x), 1))
A Date C
0 XX 2017-03-31 2017-03-31_XX
1 YY 2017-04-01 2017-04-01_YY
2 ZZ 2017-04-02 2017-04-02_ZZ
3 AA 2017-04-03 2017-04-03_AA
選項2
numpy.core.defchararray.add
非常快速的方式使用'datetime64[D]'
舍入到一天去做。 @ AndyHayden的回答
chr_add = np.core.defchararray.add
d = df.Date.values.astype('datetime64[D]').astype(str)
a = df.A.values.astype(str)
df.assign(C=chr_add(chr_add(d, '_'), a))
A Date C
0 XX 2017-03-31 2017-03-31_XX
1 YY 2017-04-01 2017-04-01_YY
2 ZZ 2017-04-02 2017-04-02_ZZ
3 AA 2017-04-03 2017-04-03_AA
選項3
敲竹槓與一小搓。我將在strftime
中加上我的下劃線'_'
...主要是,這是我將在timeit
中使用的內容。
df.assign(C=df.Date.dt.strftime('%Y-%m-%d_') + df.A)
A Date C
0 XX 2017-03-31 2017-03-31_XX
1 YY 2017-04-01 2017-04-01_YY
2 ZZ 2017-04-02 2017-04-02_ZZ
3 AA 2017-04-03 2017-04-03_AA
時序
%%timeit
chr_add = np.core.defchararray.add
d = df.Date.values.astype('datetime64[D]').astype(str)
a = df.A.values.astype(str)
chr_add(chr_add(d, '_'), a)
%timeit df.assign(C=df.apply(lambda x: '{Date:%Y-%m-%d}_{A}'.format(**x), 1))
%timeit df.assign(C=df.Date.dt.strftime('%Y-%m-%d_') + df.A)
小數據
10000 loops, best of 3: 53.2 µs per loop
1000 loops, best of 3: 1.14 ms per loop
1000 loops, best of 3: 831 µs per loop
大型數據
df = pd.concat([df] * 10000, ignore_index=True)
10 loops, best of 3: 80.3 ms per loop
1 loop, best of 3: 4.58 s per loop
1 loop, best of 3: 233 ms per loop
對不起,我對照片添加過程並不熟悉,請點擊超鏈接「enter image description here」查看數據說明。 –