Python 熊猫:计算列中的一些值
我有一个数据帧,如:Python 熊猫:计算列中的一些值,python,pandas,Python,Pandas,我有一个数据帧,如: ID value 111 1 111 0 111 1 111 0 111 0 111 0 111 1 222 1 222 0 222 0 222 1 对于每个ID,我需要一行中出现0的最大次数。 在这种情况下,由于ID111的0在一行中出现三次,而222的在一行中出现两次,因此所需的输出应该是: ID count_max_0 111 3 222 2 value\u counts不符合我的要求,因为它计算列中
ID value
111 1
111 0
111 1
111 0
111 0
111 0
111 1
222 1
222 0
222 0
222 1
对于每个ID,我需要一行中出现0
的最大次数。
在这种情况下,由于ID111
的0
在一行中出现三次,而222的在一行中出现两次,因此所需的输出应该是:
ID count_max_0
111 3
222 2
value\u counts
不符合我的要求,因为它计算列中的所有值
我该怎么做呢?这应该可以:
import numpy as np
# load data etc
...
def get_count_max_0(df):
"""
Computes the max length of a sequence of zeroes
broken by ones.
"""
values = np.array(df['value'].tolist())
# compute change points where 0 -> 1
cps_1 = np.where(
(values[1:] != values[:-1]) &
(values[1:] == 1)
)[0]
# compute change points where 1 -> 0
cps_0 = np.where(
(values[1:] != values[:-1]) &
(values[1:] == 0)
)[0]
# find lengths of zero chains
deltas = cps_1 - cps_0
# get index of max length
idx = np.where(deltas == deltas.max())[0][0]
# return max length
return deltas[idx]
# group by ID, apply get_count_max_0 to each group and
# convert resulting series back to data frame to match your expected output.
max_counts = df.groupby("ID").apply(get_count_max_0).to_frame("count_max_0")
print(max_counts)
输出为:
count_max_0
ID
111 3
222 2
你可以用
iszero = (df['value']==0)
df['group'] = (iszero.diff()==1).cumsum()
要为每行分配组号,请执行以下操作:
In [115]: df
Out[115]:
ID value group
0 111 1 0
1 111 0 1
2 111 1 2
3 111 0 3
4 111 0 3
5 111 0 3
6 111 1 4
7 222 1 4
8 222 0 5
9 222 0 5
10 222 1 6
现在,您可以按ID
和group
编号进行分组,以获得所需的值计数:
import pandas as pd
df = pd.DataFrame({'ID': [111, 111, 111, 111, 111, 111, 111, 222, 222, 222, 222],
'value': [1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1]})
iszero = (df['value']==0)
df['group'] = (iszero.diff()==1).cumsum()
counts = (df.loc[iszero] # restrict to rows which have 0 value
.groupby('ID')['group'] # group by ID, inspect the group column
.value_counts() # count the number of 0s for each (ID, group)
.groupby(level='ID') # group by ID only
.first()) # select the first (and highest) value count
print(counts)
屈服
ID
111 3
222 2
Name: group, dtype: int64
啊,可能是开始写代码了。现在听起来你只是在这里放弃了你的要求;没有告诉我们你到目前为止做了什么。这可不是个好主意。@EdChum我需要数一数零的数量,它们是直行的。它与sum()
什么是“直行”?你的意思是一行吗?@wwl我的意思是计数最大值0,看起来像0
。最大值仅为0
aggregations = {
'value': {
'total': 'sum'
}
}
dftwo = df.groupby('ID').agg(aggregations)