2017-06-26 134 views
3

是否可以比较pandas Dataframe中的列的部分?我有以下Dataframe示例,其中有4种语言已保存(en,de,nl,ua),并且每种语言应具有相同的键/相同数量的键,但具有不同的值(将静态列留在那里为完成,因为我有一个静态列,其值始终保持不变)。如何比较熊猫数据框的聚合部分?

static │ langs │ keys │ values 

x  │ en  │ key_1 │ value_en_1 
x  │ en  │ key_2 │ value_en_2 
x  │ en  │ key_3 │ value_en_3 
x  │ de  │ key_1 │ value_de_1 
x  │ de  │ key_2 │ value_de_2 
x  │ de  │ key_3 │ value_de_3 
x  │ nl  │ key_1 │ value_nl_1 
x  │ nl  │ key_2 │ value_nl_2 
x  │ ua  │ key_1 │ value_ua_1 

我需要检查哪些键,多少每种语言的缺失相比,英语一(“恩”在这里),所以像这将是一个所需的输出:

│ Lang │ Static │ # Missing │ Keys   │ 
│ de │ x  │ 0   │    │ 
│ nl │ x  │ 1   │ key_3   │ 
│ ua │ x  │ 2   │ key_2, key_3 │ 

这是我目前的进度:

import pandas as pd 

# this is read from a csv, but I'll leave it as list of lists for simplicity 
rows = [ 
    ['x', 'en', 'key_1', 'value_en_1'], 
    ['x', 'en', 'key_2', 'value_en_2'], 
    ['x', 'en', 'key_3', 'value_en_3'], 
    ['x', 'de', 'key_1', 'value_de_1'], 
    ['x', 'de', 'key_2', 'value_de_2'], 
    ['x', 'de', 'key_3', 'value_de_3'], 
    ['x', 'nl', 'key_1', 'value_nl_1'], 
    ['x', 'nl', 'key_2', 'value_nl_2'], 
    ['x', 'ua', 'key_1', 'value_en_1'] 
] 

# create DataFrame out of rows of data 
df = pd.DataFrame(rows, columns=["static", "language", "keys", "values"]) 
# print out DataFrame 
print("Dataframe: ", df) 

# first group by language and the static column 
df_grp = df.groupby(["static", "language"]) 

# try to sum the number of keys and values per each language 
df_summ = df_grp.agg(["count"]) 

# print out the sums 
print() 
print(df_summ) 

# how to compare? 
# how to get the keys? 

这是df_summ的输出:

    keys values 
       count count 
static language    
x  de   3  3 
     en   3  3 
     nl   2  2 
     ua   1  1 

在这一点上,我不知道如何继续。我很感激任何帮助/提示。

P.S.这是在Python 3.5上。

回答

3

编辑:

#get set per groups by static and language 
a = df.groupby(["static",'language'])['keys'].apply(set).reset_index() 
#filter only en language per group by static and create set 
b = df[df['language'] == 'en'].groupby("static")['keys'].apply(set) 
#subtract mapped set b and join 
c = (a['static'].map(b) - a['keys']).str.join(', ').rename('Keys') 
#substract lengths 
m = (a['static'].map(b).str.len() - a['keys'].str.len()).rename('Missing') 

df = pd.concat([a[['static','language']], m, c], axis=1) 
print (df) 
    static language Missing   Keys 
0  x  de  0    
1  x  en  0    
2  x  nl  1   key_3 
3  x  ua  2 key_3, key_2 

编辑:

我尝试改变数据:

rows = [ 
    ['x', 'en', 'key_1', 'value_en_1'], 
    ['x', 'en', 'key_2', 'value_en_2'], 
    ['x', 'en', 'key_3', 'value_en_3'], 
    ['x', 'de', 'key_1', 'value_de_1'], 
    ['x', 'de', 'key_2', 'value_de_2'], 
    ['x', 'de', 'key_3', 'value_de_3'], 
    ['x', 'nl', 'key_1', 'value_nl_1'], 
    ['x', 'nl', 'key_2', 'value_nl_2'], 
    ['x', 'ua', 'key_1', 'value_en_1'], 
    ['y', 'en', 'key_1', 'value_en_1'], 
    ['y', 'en', 'key_2', 'value_en_2'], 
    ['y', 'de', 'key_4', 'value_en_3'], 
    ['y', 'de', 'key_1', 'value_de_1'], 
    ['y', 'de', 'key_2', 'value_de_2'], 
    ['y', 'de', 'key_3', 'value_de_3'], 
    ['y', 'de', 'key_5', 'value_nl_1'], 
    ['y', 'nl', 'key_2', 'value_nl_2'], 
    ['y', 'ua', 'key_1', 'value_en_1'] 
] 

# create DataFrame out of rows of data 
df = pd.DataFrame(rows, columns=["static", "language", "keys", "values"]) 
# print out DataFrame 
#print(df) 

和输出:

print (df) 
    static language Missing   Keys 
0  x  de  0    
1  x  en  0    
2  x  nl  1   key_3 
3  x  ua  2 key_3, key_2 
4  y  de  -3    
5  y  en  0    
6  y  nl  1   key_1 
7  y  ua  1   key_2 

问题是dey静态有更多的键在en语言。

+0

好极了,谢谢。第二个解决方案似乎更复杂一点,有没有什么理由比第一个更喜欢它? –

+0

我认为在大数据中秒可以更快,如果只有一些丢失的类别。 – jezrael

+0

谢谢,另一个问题。它在哪里将其他语言与英语语言进行比较?我认为在你的解决方案中,如果说德语的键比英语的要多,那么英语的键会显示为缺少一个键,对吧? –

1

您可以首先通过分组和计算nans的数量来创建缺失的列。然后创建键列并添加静态列。

df2 = (
    df.groupby('langs')['keys'].apply(lambda x: x.values) 
     .apply(pd.Series) 
     .assign(Missing=lambda x: x.isnull().sum(axis=1)) 
) 

(
    df2[['Missing']].assign(static=df.static.iloc[0], 
          Keys=df2.apply(lambda x: ','.join(df2.loc['en'].loc[x.isnull()]),axis=1))  
) 

Out[44]: 
     Missing   Keys static 
langs        
de   0     x 
en   0     x 
nl   1  key_3  x 
ua   2 key_2,key_3  x 
1
# First we group with `language` and aggregate `static` with `min` (it's always the same anyway) 
# and `keys` with a lambda function that creates a `set`. 
In [2]: grouped = df.groupby('language').agg({'static': 'min', 'keys': lambda x: set(x)}) 

# Then we get the missing keys... 
In [3]: missing = (grouped['keys']['en'] - grouped['keys']) 

# ... and count them 
In [4]: missing_counts = missing.apply(len).rename('# Missing') 

# Then we join all of this together and replace the keys with a joined string. 
In [5]: grouped.drop('keys', axis=1).join(missing_counts).join(missing.apply(', '.join)).reset_index() 
Out[5]: 
    language static # Missing   keys 
0  de  x   0 
1  en  x   0 
2  nl  x   1   key_3 
3  ua  x   2 key_2, key_3 
1

因为你把R标签在你的问题,这里是如何与tidyrdplyr做到这一点:

library(dplyr);library(tidyr) 
df %>% 
    complete(nesting(static, langs), keys) %>% 
    group_by(langs)%>% 
    summarise(Static=max(static), 
      Missing=sum(is.na(values)), 
      Keys=toString(keys[is.na(values)]) 
      ) 

    langs Static Missing   Keys 
    <chr> <chr> <int>  <chr> 
1 de  x  0    
2 en  x  0    
3 nl  x  1  key_3 
4 ua  x  2 key_2, key_3 

数据

df <- read.table(text="static langs keys values 
'x' 'en' 'key_1' 'value_en_1' 
'x' 'en' 'key_2' 'value_en_2' 
'x' 'en' 'key_3' 'value_en_3' 
'x' 'de' 'key_1' 'value_de_1' 
'x' 'de' 'key_2' 'value_de_2' 
'x' 'de' 'key_3' 'value_de_3' 
'x' 'nl' 'key_1' 'value_nl_1' 
'x' 'nl' 'key_2' 'value_nl_2' 
'x' 'ua' 'key_1' 'value_en_1'",header=TRUE,stringsAsFactors = FALSE) 
+0

谢谢,这太棒了。我也在学习dplyr,我知道熊猫是建立在R的基础上的。 –