我有一个数据框
import pandas as pd
data = [[1, 10], [2, 15], [3, 14], [4, 15], [5, 14]]
df = pd.DataFrame(data, columns = ['Name', 'lastprice'])
如何以最有效的方式做到这一点?
答案 0 :(得分:2)
x = df["lastprice"] * 2
y = df["lastprice"].shift(1, fill_value=0) + df["lastprice"].shift(-1, fill_value=0)
df["new"] = x / y
是否如你所愿? (我不明白5)
>>> df
Name lastprice new
0 1 10 1.333333
1 2 15 1.250000
2 3 14 0.933333
3 4 15 1.071429
4 5 14 1.866667
为了避免循环,你可以改变你的值:
df["lastprice[-1]"] = df["lastprice"].shift(1) # values shifted to the bottom
df["lastprice[1]"] = df["lastprice"].shift(-1) # values shifted to the top
>>> df
Name lastprice lastprice[-1] lastprice[1]
0 1 10 NaN 15.0
1 2 15 10.0 14.0
2 3 14 15.0 15.0
3 4 15 14.0 14.0
4 5 14 15.0 NaN
答案 1 :(得分:1)
df.loc[row, col]
的使用可用于广泛的操作。虽然这可能不是最有效的方式,但它可以逐行完成工作。
data = [['', 0], [1, 10], [2, 15], [3, 14], [4, 15], [5, 14], ['', 0]]
df = pd.DataFrame(data, columns = ['Name', 'lastprice'])
df['new']=''
for i in range(1, len(df)-1):
df.loc[i, 'new'] = df.loc[i, 'lastprice']*2 / (df.loc[i-1, 'lastprice'] + df.loc[i+1, 'lastprice'])
df.drop(df.index[df['new']==''], inplace=True)
df.sort_values(by='new', ascending=False, inplace=True)
前 3 个值位于前 3 行: