简体   繁体   中英

how to exclude the zero data in an tuple dataframe with index

All: I tried to remove the zero data in my tuple data frame but can't make it. Can you please do me a favor?

My code:

mylist = [[0 for y in xrange(0, 10, 1)] for x in xrange(0, 10, 1)]
for i in xrange(0, 10, 2):
    for j in xrange(0, 10, 2):
        mylist[i][j] = '%s,%s'%(i,j)

print mylist

df = pd.DataFrame(mylist)

print df

I would like to have a (x,y) coordinates system created. Said origin is (0,0) the step of (x,y) is (2,4). I want to create a 10x 10 cooridnate list such as (0,0), (2,0)...(4,0) until (2*x,0) then loop to y (4, 0), (4,2)...(4, 2*x). Again, thanks for answers.

Updated response: First, remove the arrays of all zeros (following the for loops).

mylist = [x for x in mylist if not all([val == 0 for val in x])]

Then, remove the zeros that exist in the remaining arrays.

mylist = [[v for v in x if v != 0] for x in mylist]

This will create the following: [['0,0', '0,2', '0,4', '0,6', '0,8'], ['2,0', '2,2', '2,4', '2,6', '2,8'], ['4,0', '4,2', '4,4', '4,6', '4,8'], ['6,0', '6,2', '6,4', '6,6', '6,8'], ['8,0', '8,2', '8,4', '8,6', '8,8']].

You could also combine those two steps into one. May be slightly more time efficient, but looks a little messy.

[[v for v in x if v!=0] for x in mylist if not all([val==0 for val in x])] 

To walk through your code, your first line creates an array of arrays, filled with 0's. You then have a for loop, which is in xrange(0, 10, 2) .

You have set the step of the outer for loop to equal 2. This means it will operate on every other array in mylist .

You inner for loop also has its step argument as 2 . As such, it will only operate on every other value in the specific array that you are on.

If you would like every single zero that you initially created to be replaced with your %s,%s string, simply change the last argument for each for loop to 1 . (ie ...xrange(0, 10, 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