3 回答

TA貢獻1780條經驗 獲得超5個贊
這可能有效:
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

TA貢獻1772條經驗 獲得超5個贊
您可以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
.?

TA貢獻1807條經驗 獲得超9個贊
我不知道 R,但我看到的是您正在添加一個名為 的新列,newcol
該列的所有行的值為 3。
您還將列從col3
重命名為anothercol
。
你真的不需要執行該copy
步驟。
df2 = df.rename(columns = {'col3': 'anothercol'}) df2['newcol'] = 3
添加回答
舉報