我在python中有一个数据帧df1
,如下所示:
Type Category
a 1
b 2
c 3
d 4
预期产出:
Type
a/1
b/2
c/3
d/4
实际的数据框架要比这个大得多,因此我无法为新的数据框架键入每个单元格。
如何提取列并输出到另一个分隔了“/”的数据框架? 也许用一些for loop?
正确的pandas-y方法是使用str.cat
df['Type'] = df.Type.str.cat(others=df.Category.astype(str), sep='/')
others
包含要串联的pd.series
和要使用的分隔符sep
。
结果
Type
0 a/1
1 b/2
2 c/3
3 d/4
%%timeit
df.Type.str.cat(others=df.Category.astype(str), sep='/')
>> 286 µs ± 449 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit
df['Type']+'/'+df['Category'].astype(str)
>> 348 µs ± 5.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
两种解决方案都给出了相同的结果,但是使用str.cat
会快大约20%。