Python создание dataframe из другого

Pandas: как создать новый фрейм данных из существующего фрейма данных

Существует три распространенных способа создания нового кадра данных pandas из существующего кадра данных:

Метод 1: создание нового фрейма данных с использованием нескольких столбцов из старого фрейма данных

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

Способ 2: создать новый фрейм данных, используя один столбец из старого фрейма данных

Способ 3: создать новый фрейм данных, используя все столбцы, кроме одного, из старого фрейма данных

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

В следующих примерах показано, как использовать каждый метод со следующими пандами DataFrame:

import pandas as pd #create DataFrame old_df = pd.DataFrame() #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.

Читайте также:  Php перевести значение в строку

Примечание.Важно использовать функцию copy() при создании нового DataFrame, чтобы избежать любого SettingWithCopyWarning , если нам случится каким-либо образом изменить новый DataFrame.

Пример 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.copy#

When deep=True (default), a new object will be created with a copy of the calling object’s data and indices. Modifications to the data or indices of the copy will not be reflected in the original object (see notes below).

When deep=False , a new object will be created without copying the calling object’s data or index (only references to the data and index are copied). Any changes to the data of the original will be reflected in the shallow copy (and vice versa).

Parameters deep bool, default True

Make a deep copy, including a copy of the data and the indices. With deep=False neither the indices nor the data are copied.

Returns Series or DataFrame

Object type matches caller.

When deep=True , data is copied but actual Python objects will not be copied recursively, only the reference to the object. This is in contrast to copy.deepcopy in the Standard Library, which recursively copies object data (see examples below).

While Index objects are copied when deep=True , the underlying numpy array is not copied for performance reasons. Since Index is immutable, the underlying data can be safely shared and a copy is not needed.

Since pandas is not thread safe, see the gotchas when copying in a threading environment.

>>> s = pd.Series([1, 2], index=["a", "b"]) >>> s a 1 b 2 dtype: int64 
>>> s_copy = s.copy() >>> s_copy a 1 b 2 dtype: int64 

Shallow copy versus default (deep) copy:

>>> s = pd.Series([1, 2], index=["a", "b"]) >>> deep = s.copy() >>> shallow = s.copy(deep=False) 

Shallow copy shares data and index with original.

>>> s is shallow False >>> s.values is shallow.values and s.index is shallow.index True 

Deep copy has own copy of data and index.

>>> s is deep False >>> s.values is deep.values or s.index is deep.index False 

Updates to the data shared by shallow copy and original is reflected in both; deep copy remains unchanged.

>>> s[0] = 3 >>> shallow[1] = 4 >>> s a 3 b 4 dtype: int64 >>> shallow a 3 b 4 dtype: int64 >>> deep a 1 b 2 dtype: int64 

Note that when copying an object containing Python objects, a deep copy will copy the data, but will not do so recursively. Updating a nested data object will be reflected in the deep copy.

>>> s = pd.Series([[1, 2], [3, 4]]) >>> deep = s.copy() >>> s[0][0] = 10 >>> s 0 [10, 2] 1 [3, 4] dtype: object >>> deep 0 [10, 2] 1 [3, 4] dtype: object 

Источник

Pandas: How to Create New DataFrame from Existing DataFrame

There are three common ways to create a new pandas DataFrame from an existing DataFrame:

Method 1: Create New DataFrame Using Multiple Columns from Old DataFrame

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

Method 2: Create New DataFrame Using One Column from Old DataFrame

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

Method 3: Create New DataFrame Using All But One Column from Old DataFrame

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

The following examples show how to use each method with the following 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) 

Example 1: Create New DataFrame Using Multiple Columns from Old DataFrame

The following code shows how to create a new DataFrame using multiple columns from the old 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 

Notice that this new DataFrame only contains the points and rebounds columns from the old DataFrame.

Note: It’s important to use the copy() function when creating the new DataFrame so that we avoid any SettingWithCopyWarning if we happen to modify the new DataFrame in any way.

Example 2: Create New DataFrame Using One Column from Old DataFrame

The following code shows how to create a new DataFrame using one column from the old 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 

Notice that this new DataFrame only contains the points and column from the old DataFrame.

Example 3: Create New DataFrame Using All But One Column from Old DataFrame

The following code shows how to create a new DataFrame using all but one column from the old 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 

Notice that this new DataFrame contains all of the columns from the original DataFrame except the points column.

Additional Resources

The following tutorials explain how to perform other common tasks in Python:

Источник

Как (и зачем) сделать копию Pandas DataFrame

Всякий раз, когда вы создаете подмножество фрейма данных pandas, а затем изменяете подмножество, исходный фрейм данных также будет изменен.

По этой причине всегда рекомендуется использовать .copy() при подмножестве, чтобы любые изменения, которые вы вносите в подмножество, не применялись к исходному DataFrame.

В следующих примерах показано, как (и зачем) делать копию кадра данных pandas при подмножестве.

Пример 1: подмножество фрейма данных без копирования

Предположим, у нас есть следующие Pandas DataFrame:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame print(df) team points assists 0 A 18 5 1 B 22 7 2 C 19 7 3 D 14 9 4 E 14 12 5 F 11 9 6 G 20 9 7 H 28 4 

Теперь предположим, что мы создаем подмножество, содержащее только первые четыре строки исходного DataFrame:

#define subsetted DataFrame df_subset = df[0:4] #view subsetted DataFrame print(df_subset) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 

Если мы изменим одно из значений в подмножестве, значение в исходном DataFrame также будет изменено:

#change first value in team column df_subset. team [0] = 'X ' #view subsetted DataFrame print(df_subset) team points assists 0 X 18 5 1 B 22 7 2 C 19 7 3 D 14 9 #view original DataFrame print(df) team points assists 0 X 18 5 1 B 22 7 2 C 19 7 3 D 14 9 4 E 14 12 5 F 11 9 6 G 20 9 7 H 28 4 

Обратите внимание, что первое значение в столбце команды было изменено с «A» на «X» как в подмножестве DataFrame, так и в исходном DataFrame.

Это потому, что мы не сделали копию исходного DataFrame.

Пример 2: подмножество DataFrame с копированием

Еще раз предположим, что у нас есть следующий кадр данных pandas:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame print(df) team points assists 0 A 18 5 1 B 22 7 2 C 19 7 3 D 14 9 4 E 14 12 5 F 11 9 6 G 20 9 7 H 28 4 

Еще раз предположим, что мы создаем подмножество, содержащее только первые четыре строки исходного DataFrame, но на этот раз мы используем .copy() для создания копии исходного DataFrame:

#define subsetted DataFrame df_subset = df[0:4]. copy () 

Теперь предположим, что мы изменили первое значение в столбце team подмножества DataFrame:

#change first value in team column df_subset. team [0] = 'X ' #view subsetted DataFrame print(df_subset) team points assists 0 X 18 5 1 B 22 7 2 C 19 7 3 D 14 9 #view original DataFrame print(df) team points assists 0 A 18 5 1 B 22 7 2 C 19 7 3 D 14 9 4 E 14 12 5 F 11 9 6 G 20 9 7 H 28 4 

Обратите внимание, что первое значение в столбце команды было изменено с «A» на «X» только в подмножестве DataFrame.

Исходный DataFrame остается нетронутым, поскольку мы использовали .copy() , чтобы сделать его копию при создании подмножества.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные операции в pandas:

Источник

Оцените статью