pandas - 在行条件下应用替换函数

时间:2016-03-16 10:39:13

标签: python pandas

从此数据框开始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方法进行搜索,但是按行进行搜索。

编辑:每个字符串都可以出现在整个列的任何位置。

2 个答案:

答案 0 :(得分:3)

您可以这样做:

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

答案 1 :(得分:2)

Pandas中的布尔索引和文本比较

您可以根据boolean indexing创建string comparisons

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
相关问题