对数据帧行的操作

时间:2021-06-04 18:54:42

标签: python python-3.x pandas dataframe

我有一个数据框

import pandas as pd
data = [[1, 10], [2, 15], [3, 14], [4, 15], [5, 14]]
df = pd.DataFrame(data, columns = ['Name', 'lastprice'])
  1. 我想将 onelastprice 乘以 2(例如,x = 2* lastprice)
  2. 添加行上方和下方行的最后价格。 (比如说,y = lastprice[-1]+ lastprice[1])
  3. 将 x/y 添加到新列(比如“新建”)
  4. 对每一行重复它(对于任何不可用的值,视为零)。
  5. 打印最多 3 个“New”值及其其他行值

如何以最有效的方式做到这一点?

2 个答案:

答案 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 行:

enter image description here

相关问题