2013-07-09 5 views
1

배열이나 열의 첫 번째 값으로 na 값을 채우는 편리한 방법이 있습니까? 그래서,목록/배열이있는 팬더 채우기

dfcolors = pd.DataFrame({'Colors': ['Blue', 'Red', np.nan, 'Green', np.nan, np.nan, 'Brown']}) 

    Colors 
0 Blue 
1 Red 
2 NaN 
3 Green 
4 NaN 
5 NaN 
6 Brown 

내가 NaN의 다른 DataFrame의 값, 또는 배열 값 채우려 :

는 다음 DataFrame을 상상해

dfalt = pd.DataFrame({'Alt': ['Cyan', 'Pink']}) 

      Alt 
0   Cyan 
1   Pink 

있습니다 더 NaN이의 그때가 입력해야하는 값 일부를 NaN은 남아 있어야합니다. 채우기 값이 더 많으면 모든 값이 사용되지는 않습니다. 그래서 우리는 몇 가지 계산을해야 할 것이다 :

n_missing = len(dfcolors) - dfcolors.count().values[0]  
n_fill = min(n_missing, len(dfalt)) 

n_fill 채울 수있는 값의 양입니다. 채우기를 선택

dfcolors.Colors[pd.isnull(dfcolors.Colors)][:n_fill] 

2 NaN 
4 NaN 
Name: Colors, dtype: object 

dfalt.Alt[:n_fill] 

0 Cyan 
1 Pink 
Name: Alt, dtype: object 

값 그들 내가 좋아하는 뭔가에 붙어 :

/작성해야 할 수 있습니다 NaN의 값을 선택

을 수행 할 수 있습니다
dfcolors.Colors[pd.isnull(dfcolors.Colors)][:n_fill] = dfalt.Alt[:n_fill] 

어떤 작동하지 않습니다 ... 모든 팁이 좋을 것입니다.

내가 원하는 출력이다

Colors 
0 Blue 
1 Red 
2 Cyan 
3 Green 
4 Pink 
5 NaN 
6 Brown 

NaN이 값은 위에서 아래로 채워진다을 더가 NaN의

+1

원하는 결과는 무엇입니까? –

+0

좋은 지적, 나는 조금 질문을 편집했다. –

+0

[되돌아보기 대 사본] (http://pandas.pydata.org/pandas-docs/dev/indexing.html#indexing-view-versus-copy) (멋진 색인 생성은 항상 사본을 반환합니다) ... hmm –

답변

2
이상의 값을 기입이 있는지 충전 값은 위에서 아래로 선택

이 오히려 끔찍하지만, 널 (null)의 인덱스 반복하여 작동합니다

In [11]: nulls = dfcolors[pd.isnull(dfcolors['Colors'])] 

In [12]: for i, ni in enumerate(nulls.index[:len(dfalt)]): 
      dfcolors['Colors'].loc[ni] = dfalt['Alt'].iloc[i] 

In [13]: dfcolors 
Out[13]: 
    Colors 
0 Blue 
1 Red 
2 Cyan 
3 Green 
4 Pink 
5 NaN 
6 Brown 
3

당신은 발전기를 사용할 수 있습니다. 그렇게하면 다음과 같이 쓸 수 있습니다 :

import pandas as pd 
from pandas import np 

dfcolors = pd.DataFrame({'Colors': ['Blue', 'Red', np.nan, 'Green', np.nan, np.nan, 'Brown']}) 
dfalt = pd.DataFrame({'Alt': ['Cyan', 'Pink']}) 

gen_alt = (alt for alt in dfalt.Alt) 

for i, color in enumerate(dfcolors.Colors): 
    if not pd.isnull(color): continue 
    try: 
     dfcolors.Colors[i] = gen_alt.next() 
    except StopIteration: 
     break 
print(dfcolors) 
#  Colors 
# 0 Blue 
# 1 Red 
# 2 Cyan 
# 3 Green 
# 4 Pink 
# 5 NaN 
# 6 Brown