我有一个数据帧,如下所示:
colA colB
0 A 10
1 B 20
2 C 5
3 D 2
4 F 30
....我想比较第一列的值,以检测两个连续的递减。例如,我想报告'B‘,因为在B之后有两个连续的列1值递减。我不确定如何在不编写循环的情况下实现这一点。(如果没有办法避免循环,我想知道。)
谢谢
发布于 2019-02-17 12:21:45
您可以使用loc来执行以下操作:
desired=frame.loc[(frame["colB"]>=frame["colB"].shift(-1)) &
(frame["colB"].shift(-1)>=frame["colB"].shift(-2) )]
print(desired)输出将为:
colA colB
1 B 20如果您只希望报告值B:
desired=frame["colA"].loc[(frame["colB"]>=frame["colB"].shift(-1)) &
(frame["colB"].shift(-1)>=frame["colB"].shift(-2) )]
print(desired.values)输出将为:
['B']发布于 2019-02-17 12:33:41
是的,你可以在不使用循环的情况下做到这一点。
df = pd.DataFrame({'colA':['A', 'B', 'C', 'D', 'F'], 'colB':[10, 20, 5, 2, 30]})
>>> df['colC'] = df['colB'].diff(-1)
>>> df
colA colB colC
0 A 10 -10.0
1 B 20 15.0
2 C 5 3.0
3 D 2 -28.0
4 F 30 NaN'colC‘是连续行之间的差值。
>>> df['colD'] = np.where(df['colC'] > 0, 1, 0)
>>> df
colA colB colC colD
0 A 10 -10.0 0
1 B 20 15.0 1
2 C 5 3.0 1
3 D 2 -28.0 0
4 F 30 -1.0 0在'colD‘中,我们标记了差值大于0的标志。
>>> df1['s'] = df1['colD'].shift(-1)
>>> df1
colA colB colC colD s
0 A 10 -10.0 0 1.0
1 B 20 15.0 1 1.0
2 C 5 3.0 1 0.0
3 D 2 -28.0 0 0.0
4 F 30 -1.0 0 NaN 在列's‘中,我们将'colD’的值移位。
>>> df1['flag'] = np.where((df1['colD'] == 1) & (df1['colD'] == df1['s']), 1, 0)
>>> df1
colA colB colC colD s flag
0 A 10 -10.0 0 1.0 0
1 B 20 15.0 1 1.0 1
2 C 5 3.0 1 0.0 0
3 D 2 -28.0 0 0.0 0
4 F 30 -1.0 0 NaN 0则“flag”为必填列。
发布于 2019-02-17 12:35:28
这里需要一点逻辑
s=df.colB.diff().gt(0) # get the diff
df.loc[df.groupby(s.cumsum()).colA.transform('count').ge(3)&s,'colA'] # then we using count to see which one is more than 3 items (include the line start to two items decreasing )
Out[45]:
1 B
Name: colA, dtype: objecthttps://stackoverflow.com/questions/54729988
复制相似问题