Yan*_*ong 53 python python-2.7 pandas
我在python pandas中有一个数据帧.数据帧的结构如下:
a b c d1 d2 d3
10 14 12 44 45 78
Run Code Online (Sandbox Code Playgroud)
我想选择以d开头的列.有没有一种简单的方法来实现这一点在python中.
far*_*awa 106
你可以这样使用DataFrame.filter:
import pandas as pd
df = pd.DataFrame(np.array([[2,4,4],[4,3,3],[5,9,1]]),columns=['d','t','didi'])
>>
d t didi
0 2 4 4
1 4 3 3
2 5 9 1
df.filter(regex=("d.*"))
>>
d didi
0 2 4
1 4 3
2 5 1
Run Code Online (Sandbox Code Playgroud)
我们的想法是选择列 regex
gbr*_*ner 18
用途select:
import pandas as pd
df = pd.DataFrame([[10, 14, 12, 44, 45, 78]], columns=['a', 'b', 'c', 'd1', 'd2', 'd3'])
df.select(lambda col: col.startswith('d'), axis=1)
Run Code Online (Sandbox Code Playgroud)
结果:
d1 d2 d3
0 44 45 78
Run Code Online (Sandbox Code Playgroud)
如果您对正则表达式不满意,这是一个很好的解决方案.
特别是在更大的数据集上,矢量化方法实际上更快(超过两个数量级),并且可读性更高。我提供屏幕截图作为证明。(注意:除了我在底部写的最后几行用矢量化方法使我的观点清楚之外,其他代码均来自@Alexander的答案。)
这是供参考的代码:
import pandas as pd
import numpy as np
n = 10000
cols = ['{0}_{1}'.format(letters, number)
for number in range(n) for letters in ('d', 't', 'didi')]
df = pd.DataFrame(np.random.randn(30000, n * 3), columns=cols)
%timeit df[[c for c in df if c[0] == 'd']]
%timeit df[[c for c in df if c.startswith('d')]]
%timeit df.select(lambda col: col.startswith('d'), axis=1)
%timeit df.filter(regex=("d.*"))
%timeit df.filter(like='d')
%timeit df.filter(like='d', axis=1)
%timeit df.filter(regex=("d.*"), axis=1)
%timeit df.columns.map(lambda x: x.startswith("d"))
columnVals = df.columns.map(lambda x: x.startswith("d"))
%timeit df.filter(columnVals, axis=1)
Run Code Online (Sandbox Code Playgroud)
您可以使用列表推导来遍历DataFrame中的所有列名df,然后仅选择以'd'开头的列名。
df = pd.DataFrame({'a': {0: 10}, 'b': {0: 14}, 'c': {0: 12},
'd1': {0: 44}, 'd2': {0: 45}, 'd3': {0: 78}})
Run Code Online (Sandbox Code Playgroud)
使用列表推导来遍历数据框中的列并返回其名称(c以下是表示列名称的局部变量)。
>>> [c for c in df]
['a', 'b', 'c', 'd1', 'd2', 'd3']
Run Code Online (Sandbox Code Playgroud)
然后仅选择以“ d”开头的那些。
>>> [c for c in df if c[0] == 'd'] # As an alternative to c[0], use c.startswith(...)
['d1', 'd2', 'd3']
Run Code Online (Sandbox Code Playgroud)
最后,将此列列表传递给DataFrame。
df[[c for c in df if c.startswith('d')]]
>>> df
d1 d2 d3
0 44 45 78
Run Code Online (Sandbox Code Playgroud)
================================================== ========================
TIMINGS(在devinbost的每个评论中于2018年2月添加,声称此方法很慢...)
首先,让我们创建一个包含30k列的数据框:
n = 10000
cols = ['{0}_{1}'.format(letters, number)
for number in range(n) for letters in ('d', 't', 'didi')]
df = pd.DataFrame(np.random.randn(3, n * 3), columns=cols)
>>> df.shape
(3, 30000)
>>> %timeit df[[c for c in df if c[0] == 'd']] # Simple list comprehension.
# 10 loops, best of 3: 16.4 ms per loop
>>> %timeit df[[c for c in df if c.startswith('d')]] # More 'pythonic'?
# 10 loops, best of 3: 29.2 ms per loop
>>> %timeit df.select(lambda col: col.startswith('d'), axis=1) # Solution of gbrener.
# 10 loops, best of 3: 21.4 ms per loop
>>> %timeit df.filter(regex=("d.*")) # Accepted solution.
# 10 loops, best of 3: 40 ms per loop
Run Code Online (Sandbox Code Playgroud)
您可以使用带有索引的方法startswith(在本例中为列):
df.loc[:, df.columns.str.startswith('d')]
Run Code Online (Sandbox Code Playgroud)
或match使用正则表达式:
df.loc[:, df.columns.str.match('^d')]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34295 次 |
| 最近记录: |