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