首页 > 解决方案 > 比较 DataFrame 中的行

问题描述

我有一个 DataFrame 假设说df

import pandas as pd

data_dic = {
    "a": [0,0,1,2],
    "b": [0,3,4,5],
    "c": [6,7,8,9]
}
df = pd.DataFrame(data_dic)

它看起来像:

   a  b  c
0  0  0  6
1  0  3  7
2  1  4  8
3  2  5  9

现在我想row[0]与a 列进行比较,row[1]并在新列中发布更大的值或一些评论,比如说d

我试过使用:

for i in range(len(df):
   if (df.iloc[a][i] > df.iloc[a][i+1]):
      df[d] = "Post the greater number"

我收到一个错误:

IndexError: single positional indexer is out-of-bounds

有人能帮我吗?

标签: pythonpython-3.xpandasdataframe

解决方案


问题是当 i 位于最后一个索引时, i+1 将超出范围。

我想你可能想写:

for i in range(len(df) - 1):
  if (df.iloc[a][i] > df.iloc[a][i+1]):
    df[d] = "Post the greater number"

推荐阅读