简体   繁体   English

Pandas:基于现有数据框创建新的数据框

[英]Pandas: Create new dataframe based on existing dataframe

what is the most elegant way to create a new dataframe from an existing dataframe, by 1. selecting only certain columns and 2. renaming them at the same time?通过 1. 仅选择某些列和 2. 同时重命名它们,从现有数据帧创建新数据帧的最优雅方法是什么?

For instance I have the following dataframe, where I want to pick column B, D and F and rename them into X, Y, Z例如,我有以下数据框,我想在其中选择列 B、D 和 F 并将它们重命名为 X、Y、Z

base dataframe基础数据框

A B C D E F
1 2 3 4 5 6
1 2 3 4 5 6

new dataframe新数据框

X Y Z
2 4 6
2 4 6

您可以选择和重命名一行中的列

df2=df[['B','D','F']].rename({'B':'X','D':'Y','F':'Z'}, axis=1)

Slightly more general selection of every other column:每隔一列的更一般选择:

df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 
                   'C':[7,8,9], 'D':[10,11,12]})

df_half = df.iloc[:, ::2]

with df_half being: df_half是:

    A   C
0   1   7
1   2   8
2   3   9

You can then use the rename method mentioned in the answer by @G.然后,您可以使用@G 的答案中提到的重命名方法。 Anderson or directly assign to the columns: Anderson 或直接分配给列:

df_half.columns = ['X','Y']

returning:返回:

    X   Y
0   1   7
1   2   8
2   3   9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM