从另一个数据框中提取熊猫数据框

时间:2020-07-10 10:48:57

标签: python python-3.x pandas

假设我具有以下数据框:

                                   Date      Open      High       Low     Close     Volume         min         max  Loc
Date
2020-06-15 14:00:00 2020-06-15 14:00:00  0.000123  0.000130  0.000121  0.000128  1467828.0  0.00012081  0.00013040    0
2020-06-15 18:00:00 2020-06-15 18:00:00  0.000128  0.000129  0.000123  0.000125  1264642.0           0           0    1
2020-06-15 22:00:00 2020-06-15 22:00:00  0.000125  0.000126  0.000122  0.000123   723738.0           0           0    2

我正在尝试创建一个新的数据框,其中:

  1. 数据应为列Openminmax Loc的列,但只有minmax大于0的地方。 / li>
  2. 数据框的索引应为列Loc

现在,我知道要从另一个数据帧创建数据帧,我可以使用pandas.concat(),但是我不知道如何设置上述条件。有人可以帮我吗?

预期的输出示例:

 Loc    Open          min         max   
   0   0.000123    0.00012081  0.00013040    

2 个答案:

答案 0 :(得分:2)

首先由DataFrame.gt创建的掩码过滤器,以便与DataFrame.all比较两列中的较大列,然后按DataFrame.loc选择列,最后添加DataFrame.set_index

df = df.loc[df[['min','max']].gt(0).all(axis=1), ['Open','min','max','Loc']].set_index('Loc')
print (df)
         Open       min      max
Loc                             
0    0.000123  0.000121  0.00013

或分别比较两列和按&的掩码,以按位AND

df = df.loc[df['min'].gt(0) & df['max'].gt(0), ['Open','min','max','Loc']].set_index('Loc')

编辑:

由于错误:

在'str'和'int'的实例之间不支持

''>'

这意味着minmax列(或两者)中都有值的字符串表示形式,因此请在上述解决方案之前将值转换为数字:

df['min'] = pd.to_numeric(df['min'], errors='coerce')
df['max'] = pd.to_numeric(df['max'], errors='coerce')

答案 1 :(得分:1)

构建示例数据框:

df = pd.DataFrame(
    data={
        "Date": ["2020-06-15 14:00:00", "2020-06-15 18:00:00", "2020-06-15 22:00:00"],
        "Open": [0.000123, 0.000128, 0.000125],
        "High": [0.000130, 0.000129, 0.000126],
        "Low": [0.000121, 0.000123, 0.000122],
        "Close": [0.000128, 0.000125, 0.000123],
        "Volume": [1467828.0, 1264642.0, 723738.0],
        "min": [0.00012081, 0, 0],
        "max": [0.00013040, 0, 0],
        "Loc":  [0, 1, 2],
    }
)

df.set_index("Date", drop=False, inplace=True)

解决方案是这样:

# Set the index to a different column
# ("df2" is a copy of "df")
df2 = df.set_index("Loc")

# Keep only some columns
df2 = df2[["Open", "min", "max"]]

# Filter rows based on a condition
df2 = df2[(df2["min"] > 0) & (df2["max"] > 0)]

df2像这样:

         Open       min      max
Loc                             
0    0.000123  0.000121  0.00013