在Dataframe中查找最后一行:Python pandas模块

时间:2016-10-28 17:31:10

标签: python list pandas dataframe

我试图比较listdataframe。如果item中的list等于dataframe's row中第一列的值,我想打印出list's item之后带有dataframe's second column值的items

如果list中没有itemsdataframe's第二列中的任何list's item匹配,我只想打印list。我认为一个很好的方法就是遍历整个dataframedataframe,如果我们到达list's item的最后一行而非项目匹配,则打印只出list's item而不是dataframe's second column1003 rows X 2 columns

我需要帮助的是确定查找数据帧中最后一行所需的语法。请参阅下面的代码。

我使用的数据框是0-1002。行标签是数字col1。列标签为col2#compare items from List against items from dataframe to find matches for item in List: for idx, row in df.iterrows(): if item in row['col1']: print str(count) + " " + str(item) + " " + str(row['col2']) count=count+1 #if it's the last row in dataframe: if item not in row['col1']: print str(count) + " " + str(item)

initialize*()

2 个答案:

答案 0 :(得分:1)

#compare items from List against items from dataframe to find matches
for item in List:
    last_idx = df.iloc[-1].name
    for idx, row in df.iterrows():
        if item in row['col1']:
            print str(count) + " " + str(item) + " " + str(row['col2'])
            count=count+1

        if last_idx == idx:
            if item not in row['col1']:
                print str(count) + " " + str(item) 

考虑df

df = pd.DataFrame(np.arange(16).reshape(-1, 4),
                  pd.MultiIndex.from_product([list('XY'), [2, 5]]),
                  list('ABCD'))

df

enter image description here

最后一个索引

df.iloc[-1].name

('Y', 5)

<强> 演示

for idx, row in df.iterrows():
    last_idx = df.iloc[-1].name
    if last_idx == idx:
        print(row)

A    12
B    13
C    14
D    15
Name: (Y, 5), dtype: int64

答案 1 :(得分:0)

我发现我可以使用以下行来查找数据框中的最后一行

if count==len(df):