我知道如何append a column counting the number of elements in a group,但我需要这样做只是为了满足某个条件的群组中的数字。
例如,如果我有以下数据:
import numpy as np
import pandas as pd
columns=['group1', 'value1']
data = np.array([np.arange(5)]*2).T
mydf = pd.DataFrame(data, columns=columns)
mydf.group1 = [0,0,1,1,2]
mydf.value1 = ['P','F',100,10,0]
valueslist={'50','51','52','53','54','55','56','57','58','59','60','61','62','63','64','65','66','67','68','69','70','71','72','73','74','75','76','77','78','79','80','81','82','83','84','85','86','87','88','89','90','91','92','93','94','95','96','97','98','99','100','A','B','C','D','P','S'}
因此我的数据框如下所示:
mydf
group1 value1 0 0 P 1 0 F 2 1 100 3 1 10 4 2 0
然后,我想计算group1
中value1
所在的每个valuelist
值内的行数。
我想要的输出是:
group1 value1 count 0 0 P 1 1 0 F 1 2 1 100 1 3 1 10 1 4 2 0 0
答案 0 :(得分:2)
更改value1列的类型以匹配您的valueslist(或相反)后,您可以使用isin
获取True / False列,并使用{{1将其转换为1和0 }}。然后我们可以应用普通的groupby变换:
astype(int)
答案 1 :(得分:1)
您可以对每个group1进行分组,然后使用transform查找值是否在列表中的最大值。
mydf['count'] = mydf.groupby('group1').transform(lambda x: x.astype(str).isin(valueslist).sum())
group1 value1 count
0 0 P 1
1 0 F 1
2 1 100 1
3 1 10 1
4 2 0 0
答案 2 :(得分:1)
mydf.value1=mydf.value1.astype(str)
mydf['count']=mydf.group1.map(mydf.groupby('group1').apply(lambda x : sum(x.value1.isin(valueslist))))
mydf
Out[412]:
group1 value1 count
0 0 P 1
1 0 F 1
2 1 100 1
3 1 10 1
4 2 0 0
数据输入:
valueslist=['50','51','52','53','54','55','56','57','58','59','60','61','62','63','64','65','66','67','68','69','70','71','72','73','74','75','76','77','78','79','80','81','82','83','84','85','86','87','88','89','90','91','92','93','94','95','96','97','98','99','100','A','B','C','D','P','S']
答案 3 :(得分:0)
这是一种方法,尽管是单行:
import * as React from 'react';
import { LeftNavigation } from "../src/components/LeftNavigation";
import { mount } from 'enzyme';
import { MemoryRouter } from 'react-router-dom'
describe("<LeftNavigation />", () => {
const wrapper;
// Testing components that renders a <Link> or a <Route>, may cause
// errors and warnings about context. It is recommended to wrap your
// tests in a <StaticRouter> or <MemoryRouter>
beforeEach(() => {
wrapper = mount(
<MemoryRouter><LeftNavigation title="Protocol Vantage Points" path="/hello"/></MemoryRouter>
);
});
it("renders the title", () => {
expect(wrapper.find(".uk-h3 span").text()).toBe("Protocol Vantage Points");
});
it("renders first menu item 'On demand tests'", () => {
expect(wrapper.find("#synth-left-nav .uk-nav li a").at(0).text()).toEqual("On demand tests");
});
it("renders second menu item 'Feel status'", () => {
expect(wrapper.find("#synth-left-nav .uk-nav li a").at(1).text()).toBe("Fleet status");
});
});