Pandas如何根据部分匹配选择DataFrame的列
在数据分析和处理中,我们经常需要对数据进行筛选和过滤。对于DataFrame的列,有时候我们需要根据列名的一部分来选择需要的列。那么在Pandas中,如何根据部分匹配选择DataFrame的列呢?
阅读更多:Pandas 教程
使用.filter()方法
Pandas中DataFrame有一个.filter()方法,可以根据正则表达式从DataFrame中选出符合条件的列。这个方法可以用于选择列名中包含特定字符串的所有列。
以下是一个示例,我们使用.filter()方法选择包含‘length’字符的列:
import pandas as pd
data = {'name':['John','Tom','Susan','Kelly'],
'age':[20,25,30,35],
'length':[180,170,165,190],
'weight':[70,75,60,80]}
df = pd.DataFrame(data)
df_filter = df.filter(regex='length')
print(df_filter)
打印出的结果如下:
length
0 180
1 170
2 165
3 190
使用.loc[]方法
除了.filter()方法外,我们还可以使用.loc[]方法,通过列名的部分字符串来选择需要的列。下面的示例展示如何选择列名中包含‘weight’字符串的列:
import pandas as pd
data = {'name':['John','Tom','Susan','Kelly'],
'age':[20,25,30,35],
'length':[180,170,165,190],
'weight':[70,75,60,80]}
df = pd.DataFrame(data)
df_select = df.loc[:,df.columns.str.contains('weight')]
print(df_select)
运行后的结果如下:
weight
0 70
1 75
2 60
3 80
在上述示例中,.loc[]方法中df.columns.str.contains(‘weight’)会返回一个布尔型的Series,表示DataFrame中哪些列名包含‘weight’字符串。使用.loc[]方法可以将该布尔型Series传入,从而筛选出需要的列。
使用.ix[]方法
在Pandas 1.0.0版本中,.ix[]方法被标记为不推荐使用。但是在0.19.2版本之前,它是一种选择列名中部分字符串的常用方法。如今,在一些较旧的项目中,.ix[]方法可能仍在使用。以下是一个示例,展示如何使用.ix[]方法选择包含‘age’字符串的列:
import pandas as pd
data = {'name':['John','Tom','Susan','Kelly'],
'age':[20,25,30,35],
'length':[180,170,165,190],
'weight':[70,75,60,80]}
df = pd.DataFrame(data)
df_select = df.ix[:,df.columns.str.contains('age')]
print(df_select)
运行后的结果如下:
age
0 20
1 25
2 30
3 35
总结
本文介绍了三种方法,如何根据部分匹配选择DataFrame的列。在实际应用中,应该根据不同的情况选择合适的方法。.filter()方法可以使用正则表达式来选择列,灵活性较高。.loc[]方法在语法上能够更直观地体现使用者的意图。但是需要注意的是,在.ix[]方法使用之前,应该先确定该版本的Pandas是否在使用上存在问题。