Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

python - if str.contains() condition on a dataframe's content; AttributeError: 'str' object has no attribute 'str'

def store_press_release_links(all_sublinks_df, column_names):
    all_press_release_links_df = pd.DataFrame(columns=column_names)
    for i in range(len(all_sublinks_df)):
            if (len(all_sublinks_df.loc[i,'sub_link'].str.contains('press|releases|Press|Releases|PRESS|RELEASES'))>0):
                all_press_release_links_df.loc[i, 'link'] = all_sublinks_df[i,'link']
                all_press_release_links_df.loc[i, 'sub_link'] = all_sublinks_df[i,'sublink']
            else:
                continue
          
    all_press_release_links_df = all_press_release_links_df.drop_duplicates()
    all_press_release_links_df.reset_index(drop=True, inplace=True)
    return all_press_release_links_df

store_press_release_links() is a function that accepts a dataframe, all_sublinks_DF, which has two columns. 1. link 2. sub_link The contents of both these columns are iink names. I want to look through all the link names present in the sub_link column of the all_sublinks_DF Dataframe one by one and check if the link has the keywords ' press|releases|Press|Releases|PRESS|RELEASES' in it. If it does, then I want to store that entire row of the all_sublinks_DF Dataframe to a new dataframe all_press_release_links_df. But when I run this function it gives the error : AttributeError: 'str' object has no attribute 'str'

Where am I going wrong?

question from:https://stackoverflow.com/questions/65859254/if-str-contains-condition-on-a-dataframes-content-attributeerror-str-obje

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think what you want to do, instead of the loop just use

all_press_release_links_df = all_sublinks_df[all_sublinks_df['sub_link'].str.contains('press|releases|Press|Releases|PRESS|RELEASES')]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...