【问题标题】:I want to use python "loop" for drop list我想使用python“循环”作为下拉列表
【发布时间】:2019-01-04 10:06:17
【问题描述】:
import pandas as pd    
import os
import xlrd

os.chdir('D:\python')  
file_name='D:\python\\test.xlsx'      
sheet='test01'    
df=pd.DataFrame(pd.read_excel(file_name,sheet))  
df.drop(list(df.filter(regex = 'Abc')), axis = 1, inplace = True)
df.drop(list(df.filter(regex = 'def')), axis = 1, inplace = True)
df.drop(list(df.filter(regex = 'ghi')), axis = 1, inplace = True)
df.drop(list(df.filter(regex = 'jkl')), axis = 1, inplace = True)
df.drop(list(df.filter(regex = 'mno')), axis = 1, inplace = True)
df.drop(list(df.filter(regex = 'pqr')), axis = 1, inplace = True)

我想要一个列表中的所有变量(a 到 r),以便所有上述条件在一个句子中传递。为此,我想使用循环。对此有任何建议。

【问题讨论】:

标签: python pandas for-loop while-loop


【解决方案1】:

一些有用的函数:ord(char)返回一个字符的ASCII值; chr(int) 返回 int 的字符值 - 因此我们可以构造如下列表

drop_list = [chr(x) for x in range(ord('a'), ord('r') + 1)]
print(drop_list)

输出:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r']

【讨论】:

    【解决方案2】:

    试试这样:

    df=pd.DataFrame(pd.read_excel(file_name,sheet))  
    l = list(map(chr, range(97, ord('s'))))
    li = [''.join(l[x:x+3]) for x in range(0, len(l), 3)]
    for i in li:
        df.drop(list(df.filter(regex = i)), axis = 1, inplace = True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-31
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-12
      相关资源
      最近更新 更多