【问题标题】:Counting the occurrence of one dataframe column as a substring in another?将一个数据框列的出现计数为另一个中的子字符串?
【发布时间】:2017-02-09 12:05:17
【问题描述】:

我是 python 新手,找到了计算 df 列中硬编码子字符串的答案,但在使用另一个 df 列作为输入时无法找到答案。熊猫可以做到这一点吗?

这很混乱,但基本上我的数据框是:

ID    Info
3457  <type1><stats></id>3457<type2></id>3457<type2></id>45
234   <type2><stats></id>234
4555  <type2><stats></id>604555<type1></id>4555<type2></id>4555
2378  <stats></id>555

我已经设法计算了特定字符串的出现次数,例如

df['Type1_Count']=df['Info'].apply((lambda string: string.count("<type1>")))
df['Type2_Count']=df['Info'].apply((lambda string: string.count("<type2>")))

但是我还需要从第一列计算 ID 的出现次数,因为这些可能有错误匹配,所以确实需要对字符串“/id>”加上 ID强>列。

希望这是有道理的,感谢任何帮助。

【问题讨论】:

    标签: python python-2.7 pandas substring


    【解决方案1】:

    您可以尝试其中一种

    df = pd.DataFrame({'name':['bernard','Samy','yyy'],'digit':[2,3,3],'SearchID':['be','xx','Sam']})
    print df
    
    for ID in df['SearchID']:
        print ID, '\n', df.name.str.count(ID)
    
    Searchstr = df['SearchID'].str.cat(sep='|')
    print df.apply(lambda x: x['name'].count(x['SearchID']), axis=1)
    

    【讨论】:

    • 对于第一种方法,我收到错误“TypeError:第一个参数必须是字符串或编译模式”对于第二种方法给我“AttributeError:只能使用带有字符串值的 .str 访问器,它使用 np .object_ dtype in pandas”可能是因为我的 SearchID 是 int64?我需要转换数据类型吗?
    • 是的,这类函数需要字符串,转换成字符串试试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    相关资源
    最近更新 更多