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



假设我有以下数据帧:

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. 数据应为列OpenminmaxLoc,但仅限于minmax为>0
  2. 数据帧的索引应为列Loc

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

预期输出示例:

Loc    Open          min         max   
0   0.000123    0.00012081  0.00013040    

第一个由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"one_answers"int"的实例之间不支持,

这意味着minmax列(或两者都有(中存在值的字符串repr,因此在上面的解决方案之前将值转换为数字:

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

构建示例数据帧:

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

最新更新