【问题标题】:Problem with getting rid of specific columns [closed]摆脱特定列的问题[关闭]
【发布时间】:2020-04-08 17:26:13
【问题描述】:

我有一个包含下一列的大数据集:

cols=['plant', 'time','date','hour','NDVI','Treatment','Line','397.01', '398.32', '399.63', '400.93', '402.24', '403.55'...,'1005']

我想创建一个包含前 7 列的新数据库,然后跳过 10 列,然后拥有所有其他列。

我做过这样的事情:

df2=df_plants.iloc[:,10:]
df2.head()

但这会削减第一列,我也需要它们。

我的朋友建议我做这样的事情:

#convert the ''numeric'' columns into float

float_cols = [float(i) for i in df_plants.columns.tolist()[4:] if type(i)==str]
df_plants.columns.values[4:] = float_cols


#detector edges removal
idx1 = (np.abs(df_plants.loc[:,float_cols].columns.values - 420))
#np.argmin(idx1)
idx2 = np.argmin(np.abs(df_plants.loc[:,float_cols].columns.values - 1005.0))

但是当我应用它时,什么也没有发生,而且我不确定我是否理解他在检测器边缘部分的想法。

我的最终目标是创建包含以下列的新数据库: plant.line.treatment.time ,然后是所有大于 410 的数字列。

编辑:对我来说最好的事情是如果我能以某种方式告诉 python,如果在数字列中有负值,请将其删除。

【问题讨论】:

  • 所以想法是测试值 >410,对吧?

标签: python pandas numpy dataframe machine-learning


【解决方案1】:

尝试使用切片:

cols = df_plants.columns.tolist()
df2=df_plants[cols[:7] + cols[17:]]
df2.columns = pd.to_numeric(df2.columns.tolist(), errors='ignore')

【讨论】:

  • + with Index 对象不会连接数组,因此这是不正确的。
  • @cs95 更好???
  • 它是但我宁愿你...
  • 它起作用了,但你能解释一下为什么它需要转换成列表吗? (我是一个非常初学者)
  • cols = [*df_plants] # python >= 3.5
【解决方案2】:

我认为这里的 betetr 是将值转换为数字并按掩码过滤:

cols=['plant', 'time','date','hour','NDVI','Treatment','Line',
      '397.01', '398.32', '399.63', '400.93', '402.24', '403.55','1005']

df = pd.DataFrame(columns=cols)

num = pd.to_numeric(df.columns, errors='coerce')

df = df.loc[:, (num > 410) | num.isna()]
print (df)
Empty DataFrame
Columns: [plant, time, date, hour, NDVI, Treatment, Line, 1005]
Index: []

如果还想将值转换为数字:

def f(x):
    try:
        return float(x)
    except:
        return x

df = df.rename(columns=f)

def comp(x):
    try:
        return x > 410
    except:
        return True


df = df.loc[:, df.columns.map(comp)]
print (df)
Empty DataFrame
Columns: [plant, time, date, hour, NDVI, Treatment, Line, 1005.0]
Index: []

【讨论】:

    猜你喜欢
    • 2010-10-12
    • 2013-06-14
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多