Development Tip

Pandas 데이터 프레임에 상수 값이있는 열 추가

yourdevel 2020. 11. 15. 11:53
반응형

Pandas 데이터 프레임에 상수 값이있는 열 추가


DataFrame이 주어지면 :

np.random.seed(0)
df = pd.DataFrame(np.random.randn(3, 3), columns=list('ABC'), index=[1, 2, 3])
df

          A         B         C
1  1.764052  0.400157  0.978738
2  2.240893  1.867558 -0.977278
3  0.950088 -0.151357 -0.103219

상수 값 (예 : 0)을 포함하는 새 열을 추가하는 가장 간단한 방법은 무엇입니까?

          A         B         C  new
1  1.764052  0.400157  0.978738    0
2  2.240893  1.867558 -0.977278    0
3  0.950088 -0.151357 -0.103219    0

이것이 내 해결책이지만 이것이 NaN을 '새'열에 넣는 이유를 모르겠습니다.

df['new'] = pd.Series([0 for x in range(len(df.index))])

          A         B         C  new
1  1.764052  0.400157  0.978738  0.0
2  2.240893  1.867558 -0.977278  0.0
3  0.950088 -0.151357 -0.103219  NaN

이 풋 이유 NaN때문에 열에는 df.indexIndex당신의 오른쪽 측 객체의이 다릅니다. @zach는 0의 새 열을 할당하는 적절한 방법을 보여줍니다. 일반적 pandas으로 가능한 한 많은 인덱스 정렬을 시도합니다. 한 가지 단점은 인덱스가 일치하지 않을 때 당신이 얻을 것입니다 NaN그들이 어디에 되지 않습니다 정렬됩니다. 함께 놀러 reindexalign부분적으로이 객체와 정렬 작업을위한 약간의 직관을 얻을 방법, 완전히, 그리고 정렬되지-모든 정렬 인덱스를. 예를 들어 DataFrame.align()부분적으로 정렬 된 인덱스를 사용 하는 방법 은 다음과 같습니다.

In [7]: from pandas import DataFrame

In [8]: from numpy.random import randint

In [9]: df = DataFrame({'a': randint(3, size=10)})

In [10]:

In [10]: df
Out[10]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [11]: s = df.a[:5]

In [12]: dfa, sa = df.align(s, axis=0)

In [13]: dfa
Out[13]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [14]: sa
Out[14]:
0     0
1     2
2     0
3     1
4     0
5   NaN
6   NaN
7   NaN
8   NaN
9   NaN
Name: a, dtype: float64

매우 간단 : 직접 할당

내부 수정의 경우 직접 할당을 수행하십시오. 이 할당은 각 행에 대해 pandas에 의해 브로드 캐스팅됩니다.

df = pd.DataFrame('x', index=range(4), columns=list('ABC'))
df

   A  B  C
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x

df['new'] = 'y'
# Same as,
# df.loc[:, 'new'] = 'y'
df

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

복사본 생성 : DataFrame.assign

If you need a copy instead, use DataFrame.assign:

df.assign(new='y')

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

And, if you need to assign multiple such columns with the same value, this is as simple as,

c = ['new1', 'new2', ...]
df.assign(**dict.fromkeys(c, 'y'))

   A  B  C new1 new2
0  x  x  x    y    y
1  x  x  x    y    y
2  x  x  x    y    y
3  x  x  x    y    y

Multiple Column Assignment
Finally, if you need to assign multiple columns with different values, you can use assign with a dictionary.

c = {'new1': 'w', 'new2': 'y', 'new3': 'z'}
df.assign(**c)

   A  B  C new1 new2 new3
0  x  x  x    w    y    z
1  x  x  x    w    y    z
2  x  x  x    w    y    z
3  x  x  x    w    y    z

Here is another one liner using lambdas (create column with constant value = 10)

df['newCol'] = df.apply(lambda x: 10, axis=1)

before

df
    A           B           C
1   1.764052    0.400157    0.978738
2   2.240893    1.867558    -0.977278
3   0.950088    -0.151357   -0.103219

after

df
        A           B           C           newCol
    1   1.764052    0.400157    0.978738    10
    2   2.240893    1.867558    -0.977278   10
    3   0.950088    -0.151357   -0.103219   10

참고URL : https://stackoverflow.com/questions/24039023/add-column-with-constant-value-to-pandas-dataframe

반응형