【问题标题】:pandas apply lambda if else incorrect如果不正确,熊猫应用 lambda
【发布时间】:2018-06-20 15:40:54
【问题描述】:

具有这种格式数据的数据框

dfs = pd.read_csv('try.tsv', sep='\t')
dfs.head()
guide freq
g1   text1
g2   text1,text2,text1
g3   text1,text2,text3
g4   text1
g5   text1,text2,text3,text4,text5
g6   NaN
g7   text1,text2,text3,text4,text5,text6

填充NaN

dfs['freq'].fillna('no_guide', inplace=True)

dfs
    guide   freq
0   g1  text1
1   g2  text1,text2
2   g3  text1,text2,text3
3   g4  text1
4   g5  text1,text2,text3,text4,text5
5   g6  no_guide
6   g7  text1,text2,text3,text4,text5,text6

我需要计算文本在我尝试过的每一行中出现的次数

dfs['counts'] = dfs['freq'].str.split(',').apply(lambda x : '0' if x == 'no_guide' else len(set(x)))

我期望看到的(删除频率列之后)

guide counts
g1   1
g2   2
g3   3
g4   1
g5   5
g6   0
g5   6

我宁愿看到的

guide counts
g1   1
g2   2
g3   3
g4   1
g5   5
g6   1 #this should be g6 0
g5   6

我在我的 lambda 子句中遗漏了什么还是有其他方法可以做到这一点?

【问题讨论】:

  • 您首先替换NaN 值,然后调用.str.split(),因此您确实希望条件为0 if x == ['no_guide'] 以获得所需的输出。
  • 让我试试
  • 把它贴出来作为一个答案很有效

标签: python-2.7 pandas lambda


【解决方案1】:

这个问题是你先填充NaN,然后使用.str.split(),所以相等应该是一个列表,而不是列表的元素。您可以通过首先检查您的 lambda 函数中的 x 来看到这一点。

dfs['freq'].str.split(',')
#0                                       [text1]
#1                         [text1, text2, text1]
#2                         [text1, text2, text3]
#3                                       [text1]
#4           [text1, text2, text3, text4, text5]
#5                                    [no_guide]
#6    [text1, text2, text3, text4, text5, text6]

要检查的正确等式是 x 是否是唯一元素为 'no_guide' 的列表:

lambda x: 0 if x == ['no_guide'] else len(set(x))

由于len(set(x)) 返回一个数字,您可能还希望返回 0 而不是字符串 '0'。

【讨论】:

  • 这行得通,对不起,我忘了提及另一件事,我已经编辑了我使用的问题集,因为在某些情况下,例如这个 g2 text1,text2,text1 text1 可能出现两次,但我只会算一次
  • 是的,我刚刚注意到了。让我开始吧。
【解决方案2】:

你可以用这个:

df['freq'].fillna('no_guide', inplace=True)
df['counts'] = df['freq'].str.split(',', expand=True)\
                         .apply(lambda x: x.str.contains('text')).sum(1)

df

输出:

  guide                                 freq  counts
0    g1                                text1     1.0
1    g2                    text1,text2,text1     3.0
2    g3                    text1,text2,text3     3.0
3    g4                                text1     1.0
4    g5        text1,text2,text3,text4,text5     5.0
5    g6                             no_guide     0.0
6    g7  text1,text2,text3,text4,text5,text6     6.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 2020-08-14
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多