首页 > 解决方案 > 循环遍历python中的顺序列标题

问题描述

我有一个 df 列标题,例如:

P5_14_01 : automovil 
P5_14_02 : colectivo 
P5_14_03 : taxi app 
P5_14_04 : taxi calle, sitio u otro 
P5_14_05 : metro 
P5_14_06 : autobus, rtp o M1 
P5_14_07 : bicicleta
P5_14_08 : autobus 
P5_14_09 : moto 
P5_14_10 : trolebus
P5_14_11 : metrobus o mexibus 
P5_14_12 : tren ligero 
P5_14_13 : tren suburbano 
P5_14_14 : caminar en la calle 
P5_14_15 : mexicable 
P5_14_16 : bicitaxi 
P5_14_17 : mototaxi
P5_14_18 : transporte escolar
P5_14_19 : transporte de personal
P5_14_20 : otro

冒号后的单词是提醒(对我而言)知道我正在处理哪种信息,因此它们不会出现在 df 上。对于我想要循环并做一些计数的每一个。我的问题是,我该怎么做,因为每个列标题都是一个字符串,但最后一个密码会有所不同?换句话说,如果我想在每一列上做一些事情(对所有事情都一样),我该如何循环它们,作为它们的“名称”序列号字符串?

欢迎任何帮助。谢谢。

编辑:我的 df 的列比我正在谈论的要多得多,所以我需要一种特定的方式来解决我感兴趣的那些问题……顺便说一下,这些列分布在 df 中。

标签: pythonpandasdataframe

解决方案


def column_funtion(col_data):
    pass

columns_of_interest = [f'P5_14_{i:02}' for i in range(1, 21)]
df[columns_of_interest].apply(column_funtion, axis=0)

# If you are interested to all the columns
# df.apply(column_funtion, axis=0)

例如,给定:

def column_funtion(col_data):
    return [col_data.max(), col_data.min(), col_data.mean()]

df = pd.DataFrame(
    data=np.random.random((10, 20)),
    columns=[f'P5_14_{i:02}' for i in range(1, 21)]
)

你会得到:

   P5_14_01  P5_14_02  P5_14_03  ...  P5_14_18  P5_14_19  P5_14_20
0  0.916494  0.905081  0.829551  ...  0.869645  0.865701  0.914750
1  0.097684  0.010287  0.084090  ...  0.006364  0.052833  0.328201
2  0.498535  0.563385  0.487549  ...  0.552535  0.384080  0.603198

推荐阅读