简体   繁体   中英

Python extract data from data-set and place into a list

I want to find the amount of certain number occurring in a data set, I only care about the list[2] value.

list = [
    ['W', 1, 1],
    ['N', 3, 4], 
    ['W', 4, 0], 
    ['W', 2, 0], 
    ['S', 3, 4]
]

I was thinking of extracting the list[2] from list and placing into a different list like ( sortedlist ) and using print(sortedlist.count(4)) to count how many time "4" occurs in chosen data set.

sortedlist = []
for counts in list:
      sortedlist.append(counts[2])

Also I have another question, after the list is complete I want to input into turtle text, Does turtle text command take variables?

To count 4 s at third position of every lists in list of lists:

>>> lst = [ ['W', 1, 1], ['N', 3, 4], ['W', 4, 0], ['W', 2, 0], ['S', 3, 4] ]
>>> sum(1 for x in lst if x[2] == 4)
2

Side note : Don't name your list as list as it shadows built-in.

to count the occurrences of a specific number at a specific position in each element of the list you can use:

search = 4
position_in_row = 3

occurrences = 0
for el in list:
    if el[position_in_row-1] == search:
        occurrences += 1

print(occurrences)

I am not familiar with turtle though and would suggest to dig into the documentation or open another question.

If you are interested in each third element of each subelement try the snipped again, I edited it.

import pandas as pd

l = [['W', 1, 1],
    ['N', 3, 4], 
    ['W', 4, 0], 
    ['W', 2, 0], 
    ['S', 3, 4]]

l[2]
>>>
['W', 4, 0]

df = pd.DataFrame(l)

df
>>>
    0   1   2
0   W   1   1
1   N   3   4
2   W   4   0
3   W   2   0
4   S   3   4

df[1].value_counts()  # column wise count of each value
>>>
3    2
4    1
2    1
1    1

df.iloc[2,:].value_counts()  # row wise count for each value
>>>
W    1
0    1
4    1

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