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

2024-10-03 21:28:21 发布

您现在位置:Python中文网/ 问答频道 /正文

使用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"})

有没有更简洁的方法来做我上面所做的


Tags: columnsdfdatadttable事情col2col3
3条回答

这可能会奏效:

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

您可以使用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。 取自pandas Docs的第一个例子

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

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

相关问题 更多 >