Programing

pandas에 동시에 여러 열 추가

crosscheck 2020. 10. 24. 09:38
반응형

pandas에 동시에 여러 열 추가


나는 pandas를 처음 사용하고 pandas에 여러 열을 동시에 추가하는 방법을 알아 내려고 노력하고 있습니다. 여기에 도움을 주시면 감사하겠습니다. 이상적으로는 여러 단계를 반복하는 대신 한 단계로 수행하고 싶습니다.

import pandas as pd

df = {'col_1': [0, 1, 2, 3],
        'col_2': [4, 5, 6, 7]}
df = pd.DataFrame(df)

df[[ 'column_new_1', 'column_new_2','column_new_3']] = [np.nan, 'dogs',3]  #thought this would work here...

구문도 작동 할 것으로 예상했을 것입니다. 열 목록 구문 ( df[[new1, new2]] = ...) 을 사용하여 새 열을 만들 때 pandas에서 오른쪽이 DataFrame이어야 하기 때문에 문제가 발생합니다 ( DataFrame의 열이 열과 이름이 같은지 여부는 실제로 중요하지 않습니다. 당신이 만들고 있습니다).

구문은 기존 열에 스칼라 값을 할당하는 데 잘 작동 하며 pandas는 단일 열 구문 ( df[new1] = ...)을 사용하여 새 열에 스칼라 값을 할당하는 것도 기뻐합니다 . 따라서 해결책은 이것을 여러 개의 단일 열 할당으로 변환하거나 오른쪽에 적합한 DataFrame을 만드는 것입니다.

여기에 몇 가지 방법입니다 것입니다 작업은 :

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'col_1': [0, 1, 2, 3],
    'col_2': [4, 5, 6, 7]
})

그런 다음 다음 중 하나 :

(1) 기술적으로 이것은 세 단계이지만 한 단계처럼 보입니다.

df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]

(2) DataFrame인덱스와 일치하도록 단일 행을 편리하게 확장하므로 다음과 같이 할 수 있습니다.

df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)

(3) 새 열로 임시 데이터 프레임을 만든 다음 나중에 원래 데이터 프레임과 결합하면 잘 작동합니다.

df = pd.concat(
    [
        df,
        pd.DataFrame(
            [[np.nan, 'dogs', 3]], 
            index=df.index, 
            columns=['column_new_1', 'column_new_2', 'column_new_3']
        )
    ], axis=1
)

(4) 이전과 유사하지만 join대신 사용 concat(효율성이 떨어질 수 있음) :

df = df.join(pd.DataFrame(
    [[np.nan, 'dogs', 3]], 
    index=df.index, 
    columns=['column_new_1', 'column_new_2', 'column_new_3']
))

(5) 이것은 이전의 두 데이터 프레임보다 새 데이터 프레임을 만드는 더 "자연스러운"방법이지만 새 열은 알파벳순으로 정렬됩니다 (적어도 Python 3.6 또는 3.7 이전 ).

df = df.join(pd.DataFrame(
    {
        'column_new_1': np.nan,
        'column_new_2': 'dogs',
        'column_new_3': 3
    }, index=df.index
))

(6) @zero의 대답에서이 변형을 많이 좋아하지만 이전 열과 마찬가지로 새 열은 적어도 초기 버전의 Python에서는 항상 알파벳순으로 정렬됩니다.

df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)

(7) 이것은 흥미롭지 만 ( https://stackoverflow.com/a/44951376/3830997을 기반으로 함 ) 언제 문제가 발생할 가치가 있는지 모르겠습니다.

new_cols = ['column_new_1', 'column_new_2', 'column_new_3']
new_vals = [np.nan, 'dogs', 3]
df = df.reindex(columns=df.columns.tolist() + new_cols)   # add empty cols
df[new_cols] = new_vals  # multi-column assignment works for existing cols

(8) 결국 이길 수 없습니다 :

df['column_new_1'] = np.nan
df['column_new_2'] = 'dogs'
df['column_new_3'] = 3

참고 : 이러한 옵션의 대부분은 이미 다른 답변에서 설명되었습니다 DataFrame에 여러 열을 추가하고 기존 열을 동일하게 설정 , 그것은 팬더 DataFrame로 한 번에 여러 열을 추가 할 수 있습니까? , Pandas : DataFrame에 여러 개의 빈 열 추가


assign열 이름과 값의 사전과 함께 사용할 수 있습니다 .

In [1069]: df.assign(**{'col_new_1': np.nan, 'col2_new_2': 'dogs', 'col3_new_3': 3})
Out[1069]:
   col_1  col_2 col2_new_2  col3_new_3  col_new_1
0      0      4       dogs           3        NaN
1      1      5       dogs           3        NaN
2      2      6       dogs           3        NaN
3      3      7       dogs           3        NaN

concat 사용 :

In [128]: df
Out[128]: 
   col_1  col_2
0      0      4
1      1      5
2      2      6
3      3      7

In [129]: pd.concat([df, pd.DataFrame(columns = [ 'column_new_1', 'column_new_2','column_new_3'])])
Out[129]: 
   col_1  col_2 column_new_1 column_new_2 column_new_3
0    0.0    4.0          NaN          NaN          NaN
1    1.0    5.0          NaN          NaN          NaN
2    2.0    6.0          NaN          NaN          NaN
3    3.0    7.0          NaN          NaN          NaN

으로 무엇을하고자하는지 잘 모르겠습니다 [np.nan, 'dogs',3]. 이제 기본값으로 설정 하시겠습니까?

In [142]: df1 = pd.concat([df, pd.DataFrame(columns = [ 'column_new_1', 'column_new_2','column_new_3'])])
In [143]: df1[[ 'column_new_1', 'column_new_2','column_new_3']] = [np.nan, 'dogs', 3]

In [144]: df1
Out[144]: 
   col_1  col_2  column_new_1 column_new_2  column_new_3
0    0.0    4.0           NaN         dogs             3
1    1.0    5.0           NaN         dogs             3
2    2.0    6.0           NaN         dogs             3
3    3.0    7.0           NaN         dogs             3

지능형리스트의 사용 pd.DataFramepd.concat

pd.concat(
    [
        df,
        pd.DataFrame(
            [[np.nan, 'dogs', 3] for _ in range(df.shape[0])],
            df.index, ['column_new_1', 'column_new_2','column_new_3']
        )
    ], axis=1)

enter image description here


df = pd.DataFrame(columns = ['column1','column2'])

@Matthias Fripp의 답변에서 option2를 지적하고 싶습니다.

(2) DataFrame이 반드시 이런 방식으로 작동 할 것이라고 기대하지는 않지만

df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)

is already documented in pandas' own documentation http://pandas.pydata.org/pandas-docs/stable/indexing.html#basics

You can pass a list of columns to [] to select columns in that order. If a column is not contained in the DataFrame, an exception will be raised. Multiple columns can also be set in this manner. You may find this useful for applying a transform (in-place) to a subset of the columns.


if adding a lot of missing columns (a, b, c ,....) with the same value, here 0, i did this:

    new_cols = ["a", "b", "c" ] 
    df[new_cols] = pd.DataFrame([[0] * len(new_cols)], index=df.index)

It's based on the second variant of the accepted answer.


If you just want to add empty new columns, reindex will do the job

df
   col_1  col_2
0      0      4
1      1      5
2      2      6
3      3      7

df.reindex(list(df)+['column_new_1', 'column_new_2','column_new_3'], axis=1)
   col_1  col_2  column_new_1  column_new_2  column_new_3
0      0      4           NaN           NaN           NaN
1      1      5           NaN           NaN           NaN
2      2      6           NaN           NaN           NaN
3      3      7           NaN           NaN           NaN

full code example

import numpy as np
import pandas as pd

df = {'col_1': [0, 1, 2, 3],
        'col_2': [4, 5, 6, 7]}
df = pd.DataFrame(df)
print('df',df, sep='\n')
print()
df=df.reindex(list(df)+['column_new_1', 'column_new_2','column_new_3'], axis=1)
print('''df.reindex(list(df)+['column_new_1', 'column_new_2','column_new_3'], axis=1)''',df, sep='\n')

otherwise go for zeros answer with assign

참고URL : https://stackoverflow.com/questions/39050539/adding-multiple-columns-to-pandas-simultaneously

반응형