繁体   English   中英

如何在熊猫数据框中设置最小值和最大值?

[英]How to set the minima and maxima in a pandas dataframe?

我有以下代码:

from scipy.signal import argrelextrema

test = pd.DataFrame()
test['price'] = perf.price
test = test.dropna()
# reindex so index is int count
test.reset_index(inplace=True)

# get the peaks and valleys for the data set
peaks = argrelextrema(test.price.values, np.greater)
valleys = argrelextrema(test.price.values, np.less)

perf.price是一个数据框列。 我基本上想在测试数据帧中添加两个新列:last_peak和last_valley,并带有最后一个峰或谷的价格,但是我无法使其正常工作。

argrelextrema返回一个numpy数组,所以我已转换为pd.Series但

test.index.isin( peakSeries )

给出奇怪的结果

尝试这个:

示例数据: perf = pd.DataFrame({'price':[100.1, 1.1, 3.5, 400, 3.1, 651, 39]})

添加的代码:

test['peaks'] = False
test['valleys'] = False
test['peaks'].loc[peaks] = True
test['valleys'].loc[valleys] = True

输出示例:

   index  price  peaks  valleys
0      0  100.1  False    False
1      1    1.1  False     True
2      2    3.5  False    False
3      3  400.0   True    False
4      4    3.1  False     True
5      5  651.0   True    False
6      6   39.0  False    False

如果要添加最后一个峰和谷的列:

test['last_peak'] = test.loc[peaks[0][-1]].price
test['last_valley'] = test.loc[valleys[0][-1]].price

输出:

   index  price  peaks  valleys  last_peak  last_valley
0      0  100.1  False    False      651.0          3.1
1      1    1.1  False     True      651.0          3.1
2      2    3.5  False    False      651.0          3.1
3      3  400.0   True    False      651.0          3.1
4      4    3.1  False     True      651.0          3.1
5      5  651.0   True    False      651.0          3.1
6      6   39.0  False    False      651.0          3.1

是你想要的吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM