我有一个csv,格式如下
Time Marker
0 2104 21
1 2109 20
2 2485 21
3 2491 20
4 2867 22
5 2997 2
6 3248 23
我想计算Marker == 20之间21,22和23s的发生率。唯一有效的标记在20个代码之间预订,因此前21个无效。多个有效标记可以出现在已预订的20对中,因此我需要在一对20s之间出现21,22和23s的计数。
因此,在上面的示例中,只有索引2可以是有效代码,因为它介于两个20之间。
我有一个满足Marker == 20条件的索引列表
Indexrange = df.index[df['Marker'] == 20].tolist()
[1,
3,
10,
19,
22,
25,
29,
32,]
如何遍历索引列表并计算每对20s的每个21,22,23的发生率?
到目前为止,我有:
TwentyOnes=0
TwentyTwos=0
TwentyThrees=0
for i in Indexrange:
for index, row in df.iterrows():
if index.between(i, i+1):
if Marker == 21
Count_of_21s +=
if Marker == 22
Count_of_22s +=
if Marker == 23
Count_of_23s +=
else:
InvalidCount+=
但我正在
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-16-4a72c2a77924> in <module>()
5 for i in Indexrange:
6 for index, row in df.iterrows():
----> 7 if index.between(i,i+1):
8 print(index, row['Marker'])
AttributeError: 'int' object has no attribute 'between'
如何才能获得IndexRange中索引之间的20s /之间的值?
所需的输出为:Counts_of_21s = int,Counts_of_22s = int,Counts_of_23s = int,InvalidCount = int
答案 0 :(得分:4)
似乎你需要
df.groupby(df.Marker.eq(20).cumsum()).Marker.value_counts()
Out[1013]:
Marker Marker
0 21 1
1 20 1
21 1
2 2 1
20 1
22 1
23 1
Name: Marker, dtype: int64
更新
df=df.assign(yourid=df.Marker.eq(20).cumsum())
df.loc[(df.yourid<df.yourid.max())&(df.yourid>df.yourid.min())&(df.Marker!=20),:].groupby('yourid').Marker.value_counts()
Out[1021]:
yourid Marker
1 21 1
Name: Marker, dtype: int64
答案 1 :(得分:1)
这是我的解决方案:
import pandas as pd
csv_df = pd.read_csv('between.txt')
markers = csv_df['Marker'].tolist()
indexrange = csv_df.index[csv_df['Marker'] == 20].tolist()
list_dicts = []
for x in range(len(indexrange)-1):
currentgroup = {'21': markers[indexrange[x]:indexrange[x+1]].count(21),
'22': markers[indexrange[x]:indexrange[x+1]].count(22),
'23': markers[indexrange[x]:indexrange[x+1]].count(23)
}
list_dicts.append(currentgroup)
i = 1
for list in list_dicts:
print(f'Grouping {i}', list)
i = i+1
温家宝的表现要好得多。