繁体   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