python - 获取特定列的列名

标签 python pandas

我从一个带有神秘命名列的接口(interface)获取一个数据帧,其中我知道一些在所有列上互斥的子字符串。

一个简化的示例如下所示:

df = pandas.DataFrame({'d10432first34sf':[1,2,3],'d10432second34sf':[4,5,6]})
df
   d10432first34sf  d10432second34sf
0                1                 4
1                2                 5
2                3                 6

由于我知道列子字符串,因此我可以通过以下方式访问各个列:

df.filter(like='first')
   d10432first34sf
0                1
1                2
2                3

df.filter(like='second')
   d10432second34sf
0                 4
1                 5
2                 6

但是现在,我还需要获取每列的确切列名,这是我不知道的。我怎样才能做到这一点?

最佳答案

添加.columns:

cols = df.filter(like='first').columns
print (cols)
Index(['d10432first34sf'], dtype='object')

或者更好boolean indexingcontains :

cols = df.columns[df.columns.str.contains('first')]
print (cols)
Index(['d10432first34sf'], dtype='object')

时间不相同:

 df = pd.DataFrame({'d10432first34sf':[1,2,3],'d10432second34sf':[4,5,6]})
df = pd.concat([df]*10000, axis=1).reset_index(drop=True)
df = pd.concat([df]*1000).reset_index(drop=True)
df.columns = df.columns + pd.Series(range(10000 * 2)).astype('str')

print (df.shape)
(3000, 20000)

In [267]: %timeit df.filter(like='first').columns
10 loops, best of 3: 117 ms per loop

In [268]: %timeit df.columns[df.columns.str.contains('first')]
100 loops, best of 3: 11.9 ms per loop

关于python - 获取特定列的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43631690/

相关文章:

python - 如何检测Python应用程序中的数据竞争?

python - 如何使用 Python 3 引用某些列或行

python - 如何检查列表中元素存在的次数

python - 如何使用 Bokeh slider 更新绘图范围?

python - 如何从 django 模板中删除所有 html 标签?

python - 向量化或加速 PANDAS 列上的 Fuzzywuzzy 字符串匹配

python - 在循环中分配变量名和数据

python - 如果列表中的一个条目的键包含另一列中的字符串,则选择该条目

python - 当每个字典都有不同的键时,如何按值对字典列表进行排序?

android - 在 Python 中导入 Android 库的 aar