我有这个数据框:
df:
A B
0 a class1
1 b class12
2 a class2
3 a class1
4 b class13
所以,我将df像这样分组:
df=df.groupby(['A', 'B'])['B'].count()
我明白了
A B
a class1 2
class2 1
b class12 1
class13 1
然后我需要访问此值,并且我正考虑将它们保存在数组数组中,因此我可以轻松地读取它并将其表示在表中,如下所示:
array = [[a,[class1,1],[class2,1]],[b,[class12,1],[class13,1]]]
哪个是最好的方法?还有其他更好的选择吗?
在我真正的问题中,我不知道将拥有哪些组或组元素,并且在进行groupby操作之后,我需要列出所有这些元素。
谢谢
答案 0 :(得分:3)
[[n, [*d.B.value_counts().items()]] for n, d in df.groupby('A')]
[['a', [('class1', 2), ('class2', 1)]],
['b', [('class13', 1), ('class12', 1)]]]
如果要列表而不是元组
[[n, [*map(list, d.B.value_counts().items())]] for n, d in df.groupby('A')]
[['a', [['class1', 2], ['class2', 1]]],
['b', [['class13', 1], ['class12', 1]]]]
dict
d = {}
for a, b in df.itertuples(index=False):
d.setdefault(a, {}).setdefault(b, 0)
d[a][b] += 1
[[k, [*map(list, v.items())]] for k, v in d.items()]
[['a', [['class1', 2], ['class2', 1]]],
['b', [['class12', 1], ['class13', 1]]]]
答案 1 :(得分:1)
以您的情况
public ActionResult Index()
{
var vaultAddress = WebConfigurationManager.AppSettings["VaultUrl"];
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken));
var username = keyVaultClient.GetSecretAsync(vaultAddress, "ADUsername", ConfigurationManager.AppSettings["ADUsernameVersion"]).GetAwaiter().GetResult().Value;
var password = keyVaultClient.GetSecretAsync(vaultAddress, "ADPassword", ConfigurationManager.AppSettings["ADPasswordVersion"]).GetAwaiter().GetResult().Value;
Init();
return View();
}
public static async Task<string> GetAccessToken(string authority, string resource, string scope)
{
var clientId = WebConfigurationManager.AppSettings["ClientId"];
var clientSecret = WebConfigurationManager.AppSettings["ClientSecret"];
ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var result = await context.AcquireTokenAsync(resource, clientCredential);
return result.AccessToken;
}