programing

판다의 특정 기둥 인덱스에 기둥을 삽입하는 방법은 무엇입니까?

sourcetip 2022. 10. 2. 23:35
반응형

판다의 특정 기둥 인덱스에 기둥을 삽입하는 방법은 무엇입니까?

판다의 특정 기둥 인덱스에 기둥을 삽입할 수 있나요?

import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0

이렇게 하면 열이 생성됩니다.n의 마지막 열로서df하지만, 그 사실을 알 수 있는 방법은 없나요?df두다n처음에?

문서 참조:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html

loc = 0을 사용하면 선두에 삽입됩니다.

df.insert(loc, column, value)

df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})

df
Out: 
   B  C
0  1  4
1  2  5
2  3  6

idx = 0
new_col = [7, 8, 9]  # can be a list, a Series, an array or a scalar   
df.insert(loc=idx, column='A', value=new_col)

df
Out: 
   A  B  C
0  7  1  4
1  8  2  5
2  9  3  6

모든 행에 대해 단일 값을 원하는 경우:

df.insert(0,'name_of_column','')
df['name_of_column'] = value

편집:

다음 항목도 있습니다.

df.insert(0,'name_of_column',value)

열을 목록으로 추출하고 원하는 대로 이 항목을 마사지한 후 데이터 프레임을 다시 인덱싱할 수 있습니다.

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

편집: 이것은 한 줄로 할 수 있지만, 이것은 조금 보기 흉합니다.좀 더 깔끔한 제안이 올지도...

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2
df.insert(loc, column_name, value)

동일한 이름을 가진 다른 열이 없는 경우 이 작업이 작동합니다.지정한 이름을 가진 열이 데이터 프레임에 이미 존재하는 경우 ValueError가 발생합니다.

선택적 매개 변수를 전달할 수 있습니다.allow_duplicates와 함께Truevalue: 기존 열 이름을 사용하여 새 열을 만듭니다.

다음은 예를 제시하겠습니다.



    >>> df = pd.DataFrame({'b': [1, 2], 'c': [3,4]})
    >>> df
       b  c
    0  1  3
    1  2  4
    >>> df.insert(0, 'a', -1)
    >>> df
       a  b  c
    0 -1  1  3
    1 -1  2  4
    >>> df.insert(0, 'a', -2)
    Traceback (most recent call last):
      File "", line 1, in 
      File "C:\Python39\lib\site-packages\pandas\core\frame.py", line 3760, in insert
        self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
      File "C:\Python39\lib\site-packages\pandas\core\internals\managers.py", line 1191, in insert
        raise ValueError(f"cannot insert {item}, already exists")
    ValueError: cannot insert a, already exists
    >>> df.insert(0, 'a', -2,  allow_duplicates = True)
    >>> df
       a  a  b  c
    0 -2 -1  1  3
    1 -2 -1  2  4

여기에 아주 간단한 답이 있다.

다음과 같이 df에 'n' 열을 추가한 후 이를 수행할 수 있습니다.

import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0

df
    l   v   n
0   a   1   0
1   b   2   0
2   c   1   0
3   d   2   0

# here you can add the below code and it should work.
df = df[list('nlv')]
df

    n   l   v
0   0   a   1
1   0   b   2
2   0   c   1
3   0   d   2



However, if you have words in your columns names instead of letters. It should include two brackets around your column names. 

import pandas as pd
df = pd.DataFrame({'Upper':['a','b','c','d'], 'Lower':[1,2,1,2]})
df['Net'] = 0
df['Mid'] = 2
df['Zsore'] = 2

df

    Upper   Lower   Net Mid Zsore
0   a       1       0   2   2
1   b       2       0   2   2
2   c       1       0   2   2
3   d       2       0   2   2

# here you can add below line and it should work 
df = df[list(('Mid','Upper', 'Lower', 'Net','Zsore'))]
df

   Mid  Upper   Lower   Net Zsore
0   2   a       1       0   2
1   2   b       2       0   2
2   2   c       1       0   2
3   2   d       2       0   2
일반적인 4라인 루틴

새 열을 만들고 특정 위치에 삽입하려는 경우 언제든지 다음 4줄 루틴을 사용할 수 있습니다.loc.

df['new_column'] = ... #new column's definition
col = df.columns.tolist()
col.insert(loc, col.pop()) #loc is the column's index you want to insert into
df = df[col]

이 예에서는 다음과 같이 단순합니다.

df['n'] = 0
col = df.columns.tolist()
col.insert(0, col.pop()) 
df = df[col]

언급URL : https://stackoverflow.com/questions/18674064/how-do-i-insert-a-column-at-a-specific-column-index-in-pandas

반응형