是否可以比較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上。
好極了,謝謝。第二個解決方案似乎更復雜一點,有沒有什麼理由比第一個更喜歡它? –
我認爲在大數據中秒可以更快,如果只有一些丟失的類別。 – jezrael
謝謝,另一個問題。它在哪裏將其他語言與英語語言進行比較?我認爲在你的解決方案中,如果說德語的鍵比英語的要多,那麼英語的鍵會顯示爲缺少一個鍵,對吧? –