python 提取数据框列名,Python / Pandas数据框-返回列名

Is there a way to return the name/header of a column into a string in a pandas dataframe? I want to work with a row of data which has the same prefix. The dataframe header looks like this:

col_00 | col_01 | ... | col_51 | bc_00 | cd_00 | cd_01 | ... | cd_90

I'd like to apply a function to each row, but only from col_00 to col_51 and to cd_00 to cd_90 separately. To do this, I thought I'd collect the column names into a list, fe. to_work_with would be the list of columns starting with the prefix 'col', apply the function to df[to_work_with]. Then I'd change the to_work_with and it would contain the list of columns starting with the 'cd' prefix et cetera. But I don't know how to iterate through the column names.

So basically, the thing I'm looking for is this function:

to_work_with = column names in the df that start with "thisstring"

How can I do that? Thank you!

解决方案cols = df.columns[df.columns.str.startswith('cd')]

print (cols)

Index(['cd_00', 'cd_01', 'cd_02', 'cd_90'], dtype='object')

Sample:

print (df)

col_00 col_01 col_02 col_51 bc_00 cd_00 cd_01 cd_02 cd_90

0 1 2 3 4 5 6 7 8 9

cols = df.columns[df.columns.str.startswith('cd')]

print (cols)

Index(['cd_00', 'cd_01', 'cd_02', 'cd_90'], dtype='object')

#if want apply some function for filtered columns only

def f(x):

return x + 1

df[cols] = df[cols].apply(f)

print (df)

col_00 col_01 col_02 col_51 bc_00 cd_00 cd_01 cd_02 cd_90

0 1 2 3 4 5 7 8 9 10

Another solution with list comprehension:

cols = [col for col in df.columns if col.startswith("cd")]

print (cols)

['cd_00', 'cd_01', 'cd_02', 'cd_90']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值