Pandas:如何从现有的数据框架创建新的数据框架

231 阅读2分钟

有三种常见的方法可以从现有的DataFrame创建一个新的pandas DataFrame。

方法1:使用旧数据框架的多个列创建新的数据框架

new_df = old_df[['col1','col2']].copy()

方法2:使用旧数据框架中的一列创建新的数据框架

new_df = old_df[['col1']].copy()

方法3:使用旧数据框架中除一列外的所有列创建新的数据框架

new_df = old_df.drop('col1', axis=1)

下面的例子展示了如何在以下pandas DataFrame中使用每种方法。

import pandas as pd

#create DataFrame
old_df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                       'points': [18, 22, 19, 14, 14, 11, 20, 28],
                       'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                       'rebounds': [11, 8, 10, 6, 6, 7, 9, 12]})

#view DataFrame
print(old_df)

例子1:使用旧数据框架的多个列创建新的数据框架

下面的代码展示了如何使用旧的DataFrame中的多个列来创建一个新的DataFrame。

#create new DataFrame from existing DataFrame
new_df = old_df[['points','rebounds']].copy()

#view new DataFrame
print(new_df)

   points  rebounds
0      18        11
1      22         8
2      19        10
3      14         6
4      14         6
5      11         7
6      20         9
7      28        12

#check data type of new DataFrame
type(new_df)

pandas.core.frame.DataFrame

注意,这个新的DataFrame只包含旧DataFrame中的反弹列。

注意:在创建新的DataFrame时,使用**copy()**函数很重要,这样如果我们碰巧以任何方式修改了新的DataFrame,我们就可以避免任何SettingWithCopyWarning

示例2:使用旧数据框架的一个列创建新的数据框架

下面的代码显示了如何使用旧的DataFrame中的一列来创建一个新的DataFrame。

#create new DataFrame from existing DataFrame
new_df = old_df[['points']].copy()

#view new DataFrame
print(new_df)

   points
0      18
1      22
2      19
3      14
4      14
5      11
6      20
7      28

#check data type of new DataFrame
type(new_df)

pandas.core.frame.DataFrame

注意,这个新的DataFrame只包含旧DataFrame中的和列。

例3:使用旧数据框架中除一列外的所有列创建新的数据框架

下面的代码显示了如何使用旧的DataFrame中除一列之外的所有列来创建一个新的DataFrame。

#create new DataFrame from existing DataFrame
new_df = old_df.drop('points', axis=1)

#view new DataFrame
print(new_df)

  team  assists  rebounds
0    A        5        11
1    A        7         8
2    A        7        10
3    A        9         6
4    B       12         6
5    B        9         7
6    B        9         9
7    B        4        12

#check data type of new DataFrame
type(new_df)

pandas.core.frame.DataFrame

注意,这个新的DataFrame包含了原DataFrame的所有列,除了 点数列

其他资源

下面的教程解释了如何在Python中执行其他常见任务。

如何用列名创建空的Pandas DataFrame
如何向Pandas DataFrame添加一个列
如何向Pandas DataFrame添加多个列