使用R中的data.table,可以同时选择和分配列。假设有一个data.table,它有3列——col1、col2和col3。可以使用data.table执行以下操作:
dt2 <- dt[, .(col1, col2, newcol = 3, anothercol = col3)]
我想在熊猫身上做一些类似的事情,但看起来需要3行
df2 = df.copy()
df2['newcol'] = 3
df2.rename(columns = {"col3" : "anothercol"})
有没有更简洁的方法来做我上面所做的
这可能会奏效:
结果:
您可以使用
df.assign
进行以下操作:示例:
然后您可以将其分配给
df2
。 取自pandas Docs的第一个例子我不知道R,但我看到的是,您正在添加一个名为
newcol
的新列,该列在所有行上的值均为3。此外,您正在将列从
col3
重命名为anothercol
。您实际上不需要执行
copy
步骤相关问题 更多 >
编程相关推荐