2017-01-03 39 views
5

İki sütunlu bir df var ve NaN değerlerini göz ardı ederek iki sütunu birleştirmek istiyorum. Yakalama, bazen her iki sütunun da NaN değerlerine sahip olması, bu durumda yeni sütunun da NaN'ye sahip olmasını istiyorum. İşte örnek:pandalar, iki sütunu null değerleriyle birleştirir

df = pd.DataFrame({'foodstuff':['apple-martini', 'apple-pie', None, None, None], 'type':[None, None, 'strawberry-tart', 'dessert', None]}) 

df 
Out[10]: 
foodstuff type 
0 apple-martini None 
1 apple-pie None 
2 None strawberry-tart 
3 None dessert 
4 None None 

Ben fillna kullanmak ve bu çözmeye çalıştı:

df['foodstuff'].fillna('') + df['type'].fillna('') 

ve I got:

0  apple-martini 
1   apple-pie 
2 strawberry-tart 
3   dessert 
4     
dtype: object 

satır 4 boş değer haline gelmiştir. Bu durumda ne yok, her ikisi de birleşen sütunlar NaNs olduğu için bir NaN değeridir.

0  apple-martini 
1   apple-pie 
2 strawberry-tart 
3   dessert 
4   None  
dtype: object 

cevap

11

Kullanım fillna t ile sütun

df['foodstuff'].fillna(df['type']) 

elde edilen çıktı:

0  apple-martini 
1   apple-pie 
2 strawberry-tart 
3   dessert 
4    None 
1
Her zaman None ile yeni sütunda boş dize doldurabilir

import numpy as np 

df['new_col'].replace(r'^\s*$', np.nan, regex=True, inplace=True) 

Komple kodu:

import pandas as pd 
import numpy as np 

df = pd.DataFrame({'foodstuff':['apple-martini', 'apple-pie', None, None, None], 'type':[None, None, 'strawberry-tart', 'dessert', None]}) 

df['new_col'] = df['foodstuff'].fillna('') + df['type'].fillna('') 

df['new_col'].replace(r'^\s*$', np.nan, regex=True, inplace=True) 

df 

çıkışı: biri üzerine

foodstuff type new_col 
0 apple-martini None apple-martini 
1 apple-pie None apple-pie 
2 None strawberry-tart strawberry-tart 
3 None dessert dessert 
4 None None NaN 
1
  • fillna birlikte iki sütun
  • sum(1) olanağına
  • replace('', np.nan)
eklemek için o diğer sütun olmak değerleri dolgu
df.fillna('').sum(1).replace('', np.nan) 

0  apple-martini 
1   apple-pie 
2 strawberry-tart 
3   dessert 
4    NaN 
dtype: object 
2

Bir lambda ile combine yöntemi kullanabilirsiniz:

df['foodstuff'].combine(df['type'], lambda a, b: ((a or "") + (b or "")) or None, None) 

(a or "") döner "" bir sonra aynı mantık birleştirme uygulanır None (birleştirme eğer sonuç None olacağını ise boş bir dizedir.

İlgili konular