简体   繁体   中英

Iterate over list

Q6
4;99
3;4;8;9;14;18
2;3;8;12;18
2;3;11;18
2;3;8;18
2;3;4;5;6;7;8;9;11;12;15;16;17;18
2;3;4;8;9;10;11;13;18
1;3;4;5;6;7;13;16;17
2;3;4;5;6;7;8;9;11;12;14;15;18
3;11;18
2;3;5;8;9;11;12;13;15;16;17;18
2;5;11;18
1;2;3;4;5;8;9;11;17;18
3;7;8;11;13;14
2;3;8;18
2;13
2;3;5;8;9;11;12;13;18
2;3;4;9;11;12;18
2;3;5;9;11;18
1;2;3;4;5;6;7;8;9;11;14;15;16;17;18
2;3;8;11;13;18

import pandas as pd 
df_1 = pd.read_csv('amazon_final 29082018.csv') 
list_6 = list(df_1["Q6"]) 
list_6 = list(map(str, list_6)) 
list_7 = list(zip(list_6)) 
tem_list = [] 
for x in list_6: 
    if ('3' in x[0]): 
        tem_list.append('Fire') 
    else: 
        tem_list.append(None) 
df_1.to_csv('final.csv', index=False)

I have many such columns in data. I want to extract value '3' from this, the code which i wrote is give giving me 3 value along with 13,23,33 so on. I only want count of rows having value 3.

You need to break up the rows and convert each value to an integer. At the moment you are looking for the presence of the string "3" which is why strings like "2;13" pass the test. Try something like this:

list_6 = ["4;99", "3;4;8;9;14;18", "2;3;8;12;18", "2;3;11;18", "2;3;8;18", 
    "2;3;4;5;6;7;8;9;11;12;15;16;17;18", "2;3;4;8;9;10;11;13;18", 
    "1;3;4;5;6;7;13;16;17", "2;3;4;5;6;7;8;9;11;12;14;15;18", "3;11;18", 
    "2;3;5;8;9;11;12;13;15;16;17;18", "2;5;11;18", "1;2;3;4;5;8;9;11;17;18", 
    "3;7;8;11;13;14", "2;3;8;18", "2;13", "2;3;5;8;9;11;12;13;18", 
    "2;3;4;9;11;12;18", "2;3;5;9;11;18", 
    "1;2;3;4;5;6;7;8;9;11;14;15;16;17;18", "2;3;8;11;13;18"]
temp_list = [] 
for x in list_6: 
    numbers = [int(num_string) for num_string in x.split(';')]
    if (3 in numbers): 
        temp_list.append('Fire') 
    else: 
        temp_list.append('None') 
print(temp_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM