Skip to content
Advertisement

Find Word in a csv file and implement it using loops

I am having a dataframe named df which is having two columns,

    Company name    Company website 
0   Maersk Drilling http://www.maerskdrilling.com/ 
1   CICLAGUA SA https://simetriagrupo.com/ 
2   Enel    http://www.enel.com/ 
3   Enovos Luxembourg   http://www.enovos.lu/ 
4   DTEK    http://www.dtek.com/

Now what i am trying to implement is I am trying to find out company name where “gc” word exists and store it into new dataframe df1.

for i in range(0,a):
    if 'gc' in df['Company name'][i]:
        df1["Company Name"]= df['Company name'][i]
        df1["URL"]=df['Company website'][i]
    else:
        pass
    

but this code is showing error

      1 for i in range(0,a):
----> 2     if 'word' in df['Company name'][i]:
      3         df1["Company Name"]= df['Company name'][i]
      4         df1["URL"]=df['Company website'][i]
      5     else:

TypeError: argument of type 'float' is not iterable

Advertisement

Answer

The error you’re getting is because df[‘Company name’] is not iterable, you cannot index it. What you can do is:

df = pd.DataFrame(np.array([["name 1 gc", "gc blalkdd"], ["name 2", "asdfsa3"], ["name 3 gc", "agsd gc asd"]]),
                   columns=['Company name', 'Company website'])

df_new = pd.DataFrame(columns=['Company name', 'Company website'])

for i in range(len(df)):
    row = df.iloc[i]
    if 'gc' in row['Company name']:
        to_append_s = pd.Series(row.values.tolist(), index = df.columns)
        df_new = df_new.append(to_append_s, ignore_index=True)
    else:
        pass

Here you loop over your dataframe df, check whether column Company name contains ‘gc’, and if so: append to new_df. Result:

    Company name    Company website
0   name 1 gc       gc blalkdd
1   name 3 gc       agsd gc asd
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement