从Pandas dataFrame中删除重复项,并保留原始条件

时间:2015-10-09 16:09:18

标签: python pandas dataframe

假设我有以下DataFrame:

#!/usr/bin/python

import sys

started = None
started_line = None
for lineno, line in enumerate(sys.stdin):
    if line.startswith(' '):
        continue
    if line.strip().endswith('{'):
        started = lineno
        started_line = line.rstrip()
    if line.strip().endswith('}'):
        print("%s\t%s" % (lineno - started, started_line))

我想删除与A列相关的重复行,并且我希望保留具有值的行' PhD'在B栏中作为原件,如果我找不到博士学位,我希望保留该行的“B&B”字样。在B栏中。

我正在尝试使用

 A | B
 1 | Ms
 1 | PhD
 2 | Ms
 2 | Bs

带条件

3 个答案:

答案 0 :(得分:8)

>>> df
    A   B
0   1   Ms
1   1   Ms
2   1   Ms
3   1   Ms
4   1   PhD
5   2   Ms
6   2   Ms
7   2   Bs
8   2   PhD

使用自定义函数对数据框进行排序:

def sort_df(df, column_idx, key):
    '''Takes a dataframe, a column index and a custom function for sorting, 
    returns a dataframe sorted by that column using that function'''

    col = df.ix[:,column_idx]
    df = df.ix[[i[1] for i in sorted(zip(col,range(len(col))), key=key)]]
    return df

我们的排序功能:

cmp = lambda x:2 if 'PhD' in x else 1 if 'Bs' in x else 0

行动中:

sort_df(df,'B',cmp).drop_duplicates('A', take_last=True)

    A   B
4   1   PhD
8   2   PhD

答案 1 :(得分:5)

假设B值的唯一性给定A值,并且每个A值在B列中都有一个Bs行:

df2 = df[df['B']=="PhD"]

将为您提供包含所需博士行的数据框。

然后从df中删除所有博士和女士:

df = df[df['B']=="Bs"]

然后连接df和df2:

df3 = concat([df2, df])

然后你可以像你想要的那样使用drop_duplicates:

df3.drop_duplicates('A', inplace=True)

答案 2 :(得分:4)

考虑使用.directive('formElement', function($log, $templateCache, $compile) { return { template: '<div ng-include="\'step\' + selectedStep.step + \'.html\'">', link: function(scope, elem, attrs) { // ... nothing really here } }; }); 。他们很不错的是按字母顺序对文本进行分组/排序(除其他外)。

Categoricals
相关问题