Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

python 3.x - How do I delete key/value pair in list of dictionaries pandas env

I want to run applymap() re data in code snippet.

I tried to discard the key "P" from the list with this code: d = [i for i in data if not (i['P'] == 5.5|4.5)], And I get: TypeError: list indices must be integers or slices, not str goal: Is to eliminate key "P" and its values and also eliminate the 'empty list' before I can applymap()

**Desired Result** after running applymap() to ['A']

0     2.165
1.675
1     1.895
1.888
2     2.085
1.73
3     2.275
1.616
4     1.685
1.65
5     2.448
2.085.....

However, with 'P' key & empty [] this is not possible hence.

How can I do this in a Pandas/DataFrame environment?

data = 
    [[{'A': 2.165, 'G': 19, 'T': 180}, {'A': 1.675, 'G': 19, 'T': 181}],
    [{'A': 1.895, 'G': 19, 'T': 180}, {'A': 1.888, 'G': 19, 'T': 181}],
    [{'A': 2.085, 'G': 19, 'T': 180}, {'A': 1.73, 'G': 19, 'T': 181}],
    [{'A': 2.275, 'G': 19, 'T': 180}, {'A': 1.616, 'G': 19, 'T': 181}],
    [{'A': 1.685, 'G': 15, 'P': 5.5, 'T': 12},
    {'A': 1.65, 'G': 62, 'P': 4.5, 'T': 13}],
    [{'A': 2.448, 'G': 19, 'T': 180}, {'A': 1.54, 'G': 19, 'T': 181}],
    [{'A': 2.085, 'G': 19, 'T': 180}, {'A': 1.73, 'G': 19, 'T': 181}],
    [],
    ]
question from:https://stackoverflow.com/questions/65866540/how-do-i-delete-key-value-pair-in-list-of-dictionaries-pandas-env

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As discussed in the comments, you can use a list comprehension combined with a filter for what you need:

['
'.join(str(e['A']) for e in row if 'A' in e) for row in data if row]

# ['2.165
1.675', 
#  '1.895
1.888', 
#  '2.085
1.73', 
#  '2.275
1.616', 
#  '1.685
1.65', 
#  '2.448
1.54', 
#  '2.085
1.73']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...