pandas,groupby.agg以给定的列名返回

时间:2017-08-30 11:21:51

标签: python pandas

目前,我做

df.groupby('A')['B'].agg({'total' : np.sum})

以便聚合列的列名为total。但最近我收到了警告

FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version

那么现在首选的方式是什么?

2 个答案:

答案 0 :(得分:2)

我认为您需要 try { RequestQueue requestQueue = Volley.newRequestQueue(this); String URL = "url"; final String requestBody = "mutation M {" + "logIn" + "(" + "countryCode:" + "\"" + "1" + "\"" + "deviceType:" + "\"" + "Android" + "\"" + "osVerison:" + "\"" + "5.1.1" + "\"" + "appVerison:" + "\"" + "2.9" + "\"" + "currentCountry:" + "\"" + "IND" + "\"" + "language:" + "\"" + "ENG" + "\"" + "deviceModal:" + "\"" + "ASUS" + "" + "\")" + "{_id,countryCode,phoneNumber,emailAddress,profilePic}"; StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e("VOLLEY", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("VOLLEY", error.toString()); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("Cache-Control","no-cache"); params.put("Content-type", "application/graphql"); return params; } @Override public byte[] getBody() throws AuthFailureError { try { return requestBody == null ? null : requestBody.getBytes("utf-8"); } catch (UnsupportedEncodingException uee) { VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8"); return null; } } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String responseString = ""; if (response != null) { responseString = response.toString(); // can get more details such as response.headers } return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response)); } }; requestQueue.add(stringRequest); } catch (Exception e) { e.printStackTrace(); } reset_index中定义rename参数:

同时检查deprecate groupby agg with a dictionary when renaming

<强> 1

name

<强> 2

df = df.groupby('A')['B'].sum().reset_index(name='total')

第3

df = df.groupby('A', as_index=False)['B'].sum().rename(columns={'B':'total'})

答案 1 :(得分:2)

以下是一些方法

In [57]: df.groupby('A')['B'].sum().to_frame('total')
Out[57]:
   total
A
a      2
b      1

In [58]: df.groupby('A')['B'].agg(np.sum).to_frame('total')   # or agg('sum')
Out[58]:
   total
A
a      2
b      1

In [59]: df.groupby('A').agg({'B': np.sum}).rename(columns={'B': 'total'})
Out[59]:
   total
A
a      2
b      1