【问题标题】:If using all scalar values, you must pass an index shell returned 1如果使用所有标量值,则必须传递一个索引 shell 返回 1
【发布时间】:2018-12-04 18:43:53
【问题描述】:

我原来的dataframe是这样的

11S 420  3.65%
11N 580  0.19%
12S 450  6.13%

我想创建新的数据帧 filter1 filter2 filter3 就像原始数据帧一样,如果索引号在 1 到 8 之间,我将附加到 filter1 数据帧,如果索引号在 9 到 16 之间,我将附加到 filter2

i_r = g_e[['intrude', '8-11to10-17']]
filter1 = pd.DataFrame({"intrude":"","8-11to10-7":""})
filter2 = pd.DataFrame({"intrude":"","8-11to10-7":""})
filter3 = pd.DataFrame({"intrude":"","8-11to10-7":""})

for index1, row1 in i_r.iterrows():
    number = re.findall(r'\d{1,2}', row1.name)
    if pd.to_numeric(number) <= 8 :
         filter1.append(index1)
    if pd.to_numeric(number) <= 16:
         filter2.append(index1)
    if pd.to_numeric(number) <= 28:
         filter3.append(index1)

【问题讨论】:

  • 您的问题是什么? (并且:最后 2 个 ifs 应该是 elifs)
  • 是的 elif 是个好主意,但三个 if 也很好用,重要的是我创建空数据框并根据行追加可能没有更正

标签: python pandas


【解决方案1】:

您应该尽可能尝试使用矢量化操作。在这种情况下,不需要迭代行。这是一个将整数提取到系列的示例;然后使用pd.Series.between 应用过滤器:

df = i_r.copy()
df['index'] = df.index.str[:-1].astype(int)

df1 = df.loc[df['index'] <= 8]
df2 = df.loc[df['index'].between(9, 16)]
df3 = df.loc[df['index'].between(17, 28)]

print(df2)

     intrude 8-11to10-17  index
11S      420       3.65%     11
11N      580       0.19%     11
12S      450       6.13%     12

【讨论】:

  • 非常感谢它运行良好我从你的代码中看到了 python 的美丽。
猜你喜欢
  • 2016-11-17
  • 2017-02-19
  • 2018-05-29
  • 2023-01-24
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多