【问题标题】:Get all dataframe based in certain value in dataframe column根据数据框列中的某个值获取所有数据框
【发布时间】:2018-09-06 20:43:00
【问题描述】:

我有一个DataFrame,看起来像这样:

       import numpy as np
       import pandas as pd

       df=pd.DataFrame([['d',5,6],['a',6,6],['index',5,8],['b',3,1],['b',5,6],['index',6,7],
            ['e',2,3],['c',5,6],['index',5,8]],columns=['A','B','C'])

我想选择index 之间的所有行并创建许多数据框

我想全部获取为:

数据框1:

         A  B   C
 1       a  6   6
 2   index  5   8
 3      3   b   3   

数据框 2

                A   B   C
         4      b   5   6
         5  index   6   7
         6      c   2   3

数据帧3:

                   A   B    C
              7    c    5   6
              8 index   5   8
              9    4    3   1

数据框4:

                            A  B   C

                     11    5    2   3
                     12 index   4   2
                     13   1     2   5

【问题讨论】:

  • 我不明白“index 之间的所有行”是什么意思。如果您的意思是在列 A 处包含值 index 的那些行之间的行,那么它们与您的输出数据帧不匹配...
  • 当您只提供 9 行时,我不知道 DataFrame 4 的来源。此外,这似乎不在 index 值之间,因为它包含索引值
  • 你最初是如何得到这 4 个数据帧的?你的代码是什么?你说你想创建许多数据帧,显然是 4 个数据帧,但是你说你不知道数据帧 4 来自哪里......
  • 我看不到您想要的输出数据帧的逻辑。例如,在dataframe1中:为什么第三行是3 b 3而不是b 3 1?我看不出它与“index 之间的所有行”有什么关系。我认为您的问题不清楚。
  • 下次尝试正确地表述你的问题。根据选择的答案,您在问题中提供的 4 个数据框不是所需的输出,当您写“我想全部获取为”时,这并不清楚。

标签: python pandas numpy dataframe


【解决方案1】:
index_list = df.index[df['A'] == 'index'].tolist() # create a list of the index where df['A']=='index'
new_df = [] # empty list for dataframes
for i in index_list: # for loop
    try:
        new_df.append(df.iloc[i-1:i+2])
    except:
        pass

这将创建一个数据帧列表,您可以通过 new_df[0] new_df[1] 调用它们或使用循环将它们打印出来:

for i in range(len(new_df)):
    print(f'{new_df[i]}\n')

       A  B  C
1      a  6  6
2  index  5  8
3      b  3  1

       A  B  C
4      b  5  6
5  index  6  7
6      e  2  3

       A  B  C
7      c  5  6
8  index  5  8

【讨论】:

    猜你喜欢
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多