Python 您可以同时选择和分配数据帧中的列吗?

Python 您可以同时选择和分配数据帧中的列吗?,python,pandas,Python,Pandas,使用R中的data.table,可以同时选择和分配列。假设有一个data.table,它有3列——col1、col2和col3。可以使用data.table执行以下操作: dt2 <- dt[, .(col1, col2, newcol = 3, anothercol = col3)] 有没有更简洁的方法来完成我上面所做的工作?我不知道R,但我看到的是,您正在添加一个名为newcol的新列,该列的所有行的值均为3。 此外,您正在将列从col3重命名为anothercol 您实际上不需要执

使用R中的data.table,可以同时选择和分配列。假设有一个data.table,它有3列——col1、col2和col3。可以使用data.table执行以下操作:

dt2 <- dt[, .(col1, col2, newcol = 3, anothercol = col3)]

有没有更简洁的方法来完成我上面所做的工作?

我不知道R,但我看到的是,您正在添加一个名为
newcol
的新列,该列的所有行的值均为3。
此外,您正在将列从
col3
重命名为
anothercol

您实际上不需要执行
copy
步骤

df2 = df.rename(columns = {'col3': 'anothercol'})
df2['newcol'] = 3

您可以使用
df.assign

示例:

>>> df = pd.DataFrame({'temp_c': [17.0, 25.0]},
                  index=['Portland', 'Berkeley'])

>>> df
          temp_c
Portland    17.0
Berkeley    25.0

>>> df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32)
          temp_c  temp_f
Portland    17.0    62.6
Berkeley    25.0    77.0

>>> df.assign(newcol=3).rename(columns={"temp_c":"anothercol"}
          anothercol  newcol
Portland        17.0       3
Berkeley        25.0       3
然后您可以将其分配给
df2
。 从

中选取的第一个示例可能会起作用:

import pandas as pd

ddict = {
        'col1':['A','A','B','X'],
        'col2':['A','A','B','X'],
        'col3':['A','A','B','X'],
        }

df = pd.DataFrame(ddict)

df.loc[:, ['col1', 'col2', 'col3']].rename(columns={"col3":"anothercol"}).assign(newcol=3)
结果:

  col1 col2 anothercol  newcol
0    A    A          A       3
1    A    A          A       3
2    B    B          B       3
3    X    X          X       3

@sammywemmy为什么我们需要另一个表格数据库?熊猫工作得很好。如果您要参加竞争,您需要制定性能指标。@MarkMoretto,请查看共享的链接。原因已经在那里陈述了。基准是
  col1 col2 anothercol  newcol
0    A    A          A       3
1    A    A          A       3
2    B    B          B       3
3    X    X          X       3