![](/img/trans.png)
[英]Python Pandas: Create new rows in dataFrame based on two columns
[英]Create a new dataframe based on two columns of value in pandas dataframe
我在 python 中有一个 dataframe df1
如下:
Type Category
a 1
b 2
c 3
d 4
预期 output:
Type
a/1
b/2
c/3
d/4
实际的 dataframe 比这大得多,因此我无法为新的 dataframe 输入每个单元格。
如何将列和 output 提取到另一个 dataframe 并以“/”分隔? 也许使用一些for循环?
str.cat
正确的 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%。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.