簡體   English   中英

熊貓-按條件應用替換功能

[英]pandas - apply replace function with condition row-wise

從此數據幀df

     0     1     2
02  en    it  None
03  en  None  None
01  nl    en   fil

缺少一些值。 我試圖逐行應用替換函數,例如在偽代碼中:

def replace(x):
    if 'fil' and 'nl' in row:
        x = ''

我知道我可以做一些事情:

df.apply(f, axis=1)

具有定義如下的函數f

def f(x):
    if x[0] == 'nl' and x[2] == 'fil':
        x[0] = ''
    return x

獲得:

     0     1     2
02  en    it  None
03  en  None  None
01        en   fil

但先驗地我不知道字符串在各列中的實際位置,因此我必須使用isin方法進行搜索,但要逐行搜索。

編輯:每個字符串可以出現在整個列中的任何位置。

您可以執行以下操作:

In [111]:
def func(x):
    return x.isin(['fil']).any() &  x.isin(['nl']).any()
df.loc[df.apply(func, axis=1)] = df.replace('nl','')
df

Out[111]:
    0     1     2
2  en    it  None
3  en  None  None
1        en   fil

因此,如果行中的任何位置都存在兩個值,則該函數將返回True

In [107]:
df.apply(func, axis=1)

Out[107]:
2    False
3    False
1     True
dtype: bool

熊貓中的布爾索引和文本比較

您可以基於這樣的字符串比較來創建布爾索引

df['0'].str.contains('nl') & df['2'].str.contains('fil')

或者由於您已更新,列可能會更改:

df.isin(['fil']).any(axis=1) & df.isin(['nl']).any(axis=1)

這是測試用例:

import pandas as pd
from cStringIO import StringIO

text_file = '''
     0     1     2
02  en    it  None
03  en  None  None
01  nl    en   fil
'''

# Read in tabular data
df = pd.read_table(StringIO(text_file), sep='\s+')
print 'Original Data:'
print df
print

# Create boolean index based on text comparison
boolIndx = df.isin(['nl']).any(axis=1) & df.isin(['fil']).any(axis=1)
print 'Example Boolean index:'
print boolIndx
print

# Replace string based on boolean assignment   
df.loc[boolIndx] = df.loc[boolIndx].replace('nl', '')
print 'Filtered Data:'
print df
print

Original Data:
    0     1     2
2  en    it  None
3  en  None  None
1  nl    en   fil

Example Boolean index:
2    False
3    False
1     True
dtype: bool

Filtered Data:
    0     1     2
2  en    it  None
3  en  None  None
1        en   fil

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM