简体   繁体   中英

Python - Sorting Pandas dataframe

if I have a data frame as such:

[[19 a, 27 b, 32 c], 
[21 b, 1 a, 100 c], 
[], 
[81 c, 70 a]]

how can I sort it to be:

[[19 a, 27 b, 32 c],
[1 a, 21 b, 100 c],
[null, null, null],
[70 a, null,  81 c]]

Where all a's are in column 1, b's in column 2 and c's in column 3. Furthermore, for empty fields, I would like to fill in a null value

I am a little bit confused about your "integer-text" values, but something like this can solve your problem:

li = [['19 a', '27 b', '32 c'], 
      ['21 b', '1 a', '100 c'], 
      [], 
      ['81 c', '70 a']]

def parse(item):
    parsed = []
    for letter in ['a', 'b', 'c']:
        match = ''.join(i for i in item if letter in i)
        parsed.append(match)
    return parsed

parsed = [parse(item) for item in li]
print(parsed)

output:

[['19 a', '27 b', '32 c'], 
 ['1 a', '21 b', '100 c'], 
 ['', '', ''], 
 ['70 a', '', '81 c']]

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