[英]Python/Pandas dataframe - return column name
有没有一种方法可以将列的名称/标题返回到pandas数据框中的字符串? 我想使用具有相同前缀的数据行。 数据帧头看起来像这样:
col_00 | col_01 | ... | col_51 | bc_00 | cd_00 | cd_01 | ... | cd_90
我想对每行应用一个函数,但是仅从col_00
到col_51
以及从cd_00
到cd_90
。 为此,我想我会将列名称收集到一个列表中,例如fe。 to_work_with
将是以前缀'col'开头的列的列表,将该函数应用于df[to_work_with]
。 然后,我将更改to_work_with
,它将包含以“ cd”前缀等开头的列的列表。 但是我不知道如何遍历列名。
所以基本上,我正在寻找的东西是这个功能:
to_work_with = column names in the df that start with "thisstring"
我怎样才能做到这一点? 谢谢!
您可以将boolean indexing
与str.startswith
一起str.startswith
:
cols = df.columns[df.columns.str.startswith('cd')]
print (cols)
Index(['cd_00', 'cd_01', 'cd_02', 'cd_90'], dtype='object')
样品:
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
list comprehension
另一种解决方案:
cols = [col for col in df.columns if col.startswith("cd")]
print (cols)
['cd_00', 'cd_01', 'cd_02', 'cd_90']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.