【问题标题】:pandas dataframe get row numbers and add to list熊猫数据框获取行号并添加到列表
【发布时间】:2017-09-15 21:27:53
【问题描述】:

假设我们有一个熊猫数据框,它具有如下所示的三个特征。

每一行代表一个客户,每一列代表这个客户的一些特征。

我想获取行号并将它们添加到列表中,或者根据它们的特征值不将它们添加到列表中。

假设,如果 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]

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

这样怎么样?

ls = []

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

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

【讨论】:

  • 如何将一个数据框添加到另一个而不是列表?你知道吗?
  • @melih.tt pd.concat([df1, df2])
【解决方案2】:

不是很清楚......但也许是这样的:

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

[0, 1, 3, 4]

【讨论】:

    【解决方案3】:

    您想将索引输出为列表。

    print(df[df['feature2'] > 500].index.tolist())
    
    [0, 1, 3]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 2014-04-15
      • 2021-04-19
      • 1970-01-01
      • 2021-03-20
      相关资源
      最近更新 更多