Python Pandas 复制列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44009896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:37:06 来源:igfitidea点击:
Python Pandas Copy Columns
提问by RMichalowski
How do I copy multiple columns from one dataframe to a new dataframe? it would also be nice to rename them at the same time
如何将多个列从一个数据帧复制到新的数据帧?同时重命名它们也会很好
df2['colA']=df1['col-a'] #This works
df2['colA', 'colB']=df1['col-a', 'col-b'] #Tried and Failed
Thanks
谢谢
回答by Andy Hayden
You have to use double brackets:
你必须使用双括号:
df2[['colA', 'colB']] = df1[['col-a', 'col-b']]
回答by Lukas
Following also works:
以下也有效:
# original DataFrame
df = pd.DataFrame({'a': ['hello', 'cheerio', 'hi', 'bye'], 'b': [1, 0, 1, 0]})
# new DataFrame created from 2 original cols (new cols renamed)
df_new = pd.DataFrame(columns=['greeting', 'mode'], data=df[['a','b']].values)
If you want to use condition for the new dataframe:
如果要对新数据框使用条件:
df_new = pd.DataFrame(columns=['farewell', 'mode'], data=df[df['b']==0][['a','b']].values)
Or if you want use just particular rows (index), you can use "loc":
或者,如果您只想使用特定行(索引),您可以使用“loc”:
df_new = pd.DataFrame(columns=['greetings', 'mode'], data=df.loc[2:3][['a','b']].values)
# if you need preserve row index, then add index=... as argument, like:
df_new = pd.DataFrame(columns=['farewell', 'mode'], data=df.loc[2:3][['a','b']].values,
index=df.loc[2:3].index )