2012-06-10 8 views
19

에 두 개의 열을 결합 : foobar 다르게 명명 아직 동일한 데이터를 포함하는 열입니다팬더 : 나는 그것에 여러 열이있는 팬더 <code>DataFrame</code>을 가지고 DataFrame

Index: 239897 entries, 2012-05-11 15:20:00 to 2012-06-02 23:44:51 
Data columns: 
foo     11516 non-null values 
bar     228381 non-null values 
Time_UTC    239897 non-null values 
dtstamp    239897 non-null values 
dtypes: float64(4), object(1) 

. bar의 이름을 유지하면서 foo을 구성하는 행을 bar으로 옮기는 방법이 있습니까? 막대를 만든 NaN의 값이다

Index: 239897 entries, 2012-05-11 15:20:00 to 2012-06-02 23:44:51 
Data columns: 
bar     239897 non-null values 
Time_UTC    239897 non-null values 
dtstamp    239897 non-null values 
dtypes: float64(4), object(1) 

foo에서 값으로 대체했다 : 같이

이 결국 DataFrame 나타나야.

pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df) 

는 데이터가 새 열 bar이 될 것을 원하는 경우에, 다만 df['bar']에 결과를 할당합니다

답변

21

이 시도해보십시오.

+0

; 내가 무엇을 놓치고 있는지 잘 모르겠습니다. – BFTM

+0

판다의 버전은 무엇입니까? 이 함수는 다음 위치에서 문서화됩니다 : http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-objects – BrenBarn

+0

나는 concat 함수가 포함되어 있지 않은 pandas ver 0.6.1을 실행하고있었습니다. v 0.7.3으로의 업그레이드는 이름 공간으로 concat를 가져옵니다. 매력처럼 작동합니다! 감사. – BFTM

21

직접 fillna 사용하고 열 '바'

df['bar'].fillna(df['foo'], inplace=True) 
del df['foo'] 

일반적인 예에 ​​결과를 할당 할 수 있습니다

import pandas as pd 
#creating the table with two missing values 
df1 = pd.DataFrame({'a':[1,2],'b':[3,4]}, index = [1,2]) 
df2 = pd.DataFrame({'b':[5,6]}, index = [3,4]) 
dftot = pd.concat((df1, df2)) 
print dftot 
#creating the dataframe to fill the missing values 
filldf = pd.DataFrame({'a':[7,7,7,7]}) 

#filling 
print dftot.fillna(filldf) 
+0

그러나 filldf는 0..3으로 인덱싱되므로 dftot는 1..4로 인덱싱되지만 dftot.fillna (filldf) [ 'a'] [4]는 nan이됩니다. 7.0이 아니야 –

5

또 다른 옵션을 프레임에 .apply() 방법을 사용합니다. 당신은 ... 기존의 데이터에 대한 존중과 (적어도 0.12부터)

import pandas as pd 
import numpy as np 

# get your data into a dataframe 

# replace content in "bar" with "foo" if "bar" is null 
df["bar"] = df.apply(lambda row: row["foo"] if row["bar"] == np.NaN else row["bar"], axis=1) 

# note: change 'np.NaN' with null values you have like an empty string 
+0

catch @Veenit에게 감사드립니다. – openwonk

3

현대 팬더 버전을 열을 재 할당 DataFrame 및 시리즈 개체에 대한 combine_first() and update() 방법을 할 수 있습니다. 당신의 DataFrame가 df 불렸다 예를 들어, 당신은 할 것 :

df.bar.combine_first(df.foo) 

에만 foo 열을 일치하도록 bar 열의 할머니 값을 변경하는 것, 그래서 인플레 이스 할 것입니다. bar의 비 Nan 값을 foo의 값으로 덮어 쓰려면 update() 메서드를 사용합니다.

2

numpy도이 작업을 수행 할 수 있습니다. 나는`팬더 네임 스페이스의 함수로 concat`을보고 있지 않다

df['bar'] = np.where(pd.isnull(df['bar']),df['foo'],df['bar'])