簡體   English   中英

熊貓數據框獲取行號並添加到列表

[英]pandas dataframe get row numbers and add to list

假設我們有一個熊貓數據框,具有以下所示的三個功能。

在此處輸入圖片說明

每行代表一個客戶,每列代表該客戶的某些功能。

我想獲取行號並將其添加到列表中,或者不根據其功能值將它們添加到列表中。

假設,如果FEATUREA小於100或FEATUREB大於500,我們想查找行號。

我已經為此編寫了一些代碼,如下所示。

import pandas as pd

d = [{'feature1': 100, 'feature2': 520, 'feature3': 54},
     {'feature1': 102, 'feature2': 504, 'feature3': 51},
     {'feature1': 241, 'feature2': 124, 'feature3': 4},
     {'feature1': 340, 'feature2': 830, 'feature3': 700},
     {'feature1': 98, 'feature2': 430, 'feature3': 123}]

df = DataFrame(d)
print(df)
print("----")

dataframe1 = df[(df['feature1'] < 100)]
dataframe2 = df[(df['feature2'] > 500)]

print(dataframe1)
print(dataframe2)
# here I would like to get row number temp and add them to result list

程序輸出

      feature1  feature2  feature3
0       100       520        54
1       102       504        51
2       241       124         4
3       340       830       700
4        98       430       123
----
   feature1  feature2  feature3
4        98       430       123
   feature1  feature2  feature3
0       100       520        54
1       102       504        51
3       340       830       700

我不知道如何組合dataframe1和dataframe2,然后獲取它們的行號。 如果您知道該怎么做,請分享一下嗎?

我想看到這樣的結果列表

result = [ 4, 0, 1, 3]

尚不清楚...但是也許這:

df.query('feature1 < 100 | feature2 > 500').index.tolist()

[0, 1, 3, 4]

這樣怎么樣

ls = []

ls.extend(df.index[(df['feature1'] < 100 )])
ls.extend(df.index[(df['feature2'] > 500 )])

print(ls)
[4, 0, 1, 3]

您想將索引輸出為列表。

print(df[df['feature2'] > 500].index.tolist())

[0, 1, 3]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM