使用 Pandas 中的 apply 函数,按行进行条件替换

3

从这个数据框 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个回答

4
您可以像这样做:

您可以像这样做:

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

谢谢,实际上我不想覆盖第一列中的所有值,只想更改满足条件的行和列的值(例如,前两行中的 en 值应该保留...)。 - Fabio Lamanna
谢谢!抱歉还有一些错别字需要修正,赋值函数现在应该写成:df.loc[df.apply(func, axis=1)] = df.replace('nl','') - Fabio Lamanna
那么“nl”可以出现在任何列而不仅仅是第一列吗? - EdChum
@tmthydvnprt 是的,谢谢你。我知道apply在处理大型数据框时速度会比较慢。 - Fabio Lamanna
@FabioLamanna 现在这个任务也与列无关了。 - tmthydvnprt
显示剩余2条评论

2

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

您可以基于字符串比较创建布尔索引,就像这样:

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

谢谢。我尝试为您和未来的观众提供链接,以便深入了解具体细节。 - tmthydvnprt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接