import pandas as pddf = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})
In [131]: %timeit df["Year"].map(str)10000 loops, best of 3: 132 us per loop
In [132]: %timeit df["Year"].astype(str)10000 loops, best of 3: 82.2 us per loop
[''.join(i) for i in zip(df["Year"].map(str),df["quarter"])]
或稍慢但更紧凑:
df.Year.str.cat(df.quarter)
更大的数据集(>150行)
df['Year'].astype(str) + df['quarter']
更新:定时图熊猫0.23.4
让我们在200K行DF上测试它:
In [250]: dfOut[250]:Year quarter0 2014 q11 2015 q2
In [251]: df = pd.concat([df] * 10**5)
In [252]: df.shapeOut[252]: (200000, 2)
更新:使用Pandas的新计时0.19.0
定时没有CPU/GPU优化(从最快到最慢排序):
In [107]: %timeit df['Year'].astype(str) + df['quarter']10 loops, best of 3: 131 ms per loop
In [106]: %timeit df['Year'].map(str) + df['quarter']10 loops, best of 3: 161 ms per loop
In [108]: %timeit df.Year.str.cat(df.quarter)10 loops, best of 3: 189 ms per loop
In [109]: %timeit df.loc[:, ['Year','quarter']].astype(str).sum(axis=1)1 loop, best of 3: 567 ms per loop
In [110]: %timeit df[['Year','quarter']].astype(str).sum(axis=1)1 loop, best of 3: 584 ms per loop
In [111]: %timeit df[['Year','quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1)1 loop, best of 3: 24.7 s per loop
定时使用CPU/GPU优化:
In [113]: %timeit df['Year'].astype(str) + df['quarter']10 loops, best of 3: 53.3 ms per loop
In [114]: %timeit df['Year'].map(str) + df['quarter']10 loops, best of 3: 65.5 ms per loop
In [115]: %timeit df.Year.str.cat(df.quarter)10 loops, best of 3: 79.9 ms per loop
In [116]: %timeit df.loc[:, ['Year','quarter']].astype(str).sum(axis=1)1 loop, best of 3: 230 ms per loop
In [117]: %timeit df[['Year','quarter']].astype(str).sum(axis=1)1 loop, best of 3: 230 ms per loop
In [118]: %timeit df[['Year','quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1)1 loop, best of 3: 9.38 s per loop
In [1]: import pandas as pd
In [2]: df = pd.DataFrame([[0, 'the', 'quick', 'brown'],...: [1, 'fox', 'jumps', 'over'],...: [2, 'the', 'lazy', 'dog']],...: columns=['c0', 'c1', 'c2', 'c3'])
In [3]: def str_join(df, sep, *cols):...: from functools import reduce...: return reduce(lambda x, y: x.astype(str).str.cat(y.astype(str), sep=sep),...: [df[col] for col in cols])...:
In [4]: df['cat'] = str_join(df, '-', 'c0', 'c1', 'c2', 'c3')
In [5]: dfOut[5]:c0 c1 c2 c3 cat0 0 the quick brown 0-the-quick-brown1 1 fox jumps over 1-fox-jumps-over2 2 the lazy dog 2-the-lazy-dog
def madd(x):"""Performs element-wise string concatenation with multiple input arrays.
Args:x: iterable of np.array.
Returns: np.array."""for i, arr in enumerate(x):if type(arr.item(0)) is not str:x[i] = x[i].astype(str)return reduce(np.core.defchararray.add, x)
例如:
data = list(zip([2000]*4, ['q1', 'q2', 'q3', 'q4']))df = pd.DataFrame(data=data, columns=['Year', 'quarter'])df['period'] = madd([df[col].values for col in ['Year', 'quarter']])
df
Year quarter period0 2000 q1 2000q11 2000 q2 2000q22 2000 q3 2000q33 2000 q4 2000q4
%timeit df['Year'].values.astype(str) + df.quarter71.1 ms ± 3.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit df['Year'].astype(str) + df['quarter']565 ms ± 22.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# be cautious about the separator, some symbols may cause "SyntaxError: EOL while scanning string literal".# e.g. ";;" as separator would raise the SyntaxError
separator = "&&"
# pd.Series.str.cat() method does not work to concatenate / combine two columns with int value and str value. This would raise "AttributeError: Can only use .cat accessor with a 'category' dtype"
df["period"] = df["Year"].map(str) + separator + df["quarter"]df["period"] = df[['Year','quarter']].apply(lambda x : '{} && {}'.format(x[0],x[1]), axis=1)df["period"] = df.apply(lambda x: f'{x["Year"]} && {x["quarter"]}', axis=1)