pandas 根据列名称创建 DataFrame 的子集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20903071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a subset of a DataFrame depending on column name
提问by user2761786
I have a pandas DataFrame called timedatawith different column names, some of which contain the word Vibration, some eccentricity. Is is possible to create a dataframe of just the columns containing the word Vibration?
我有一个timedata用不同列名调用的 Pandas DataFrame ,其中一些包含单词 Vibration 和一些偏心。是否可以创建仅包含“振动”一词的列的数据框?
I have tried using
我试过使用
vib=[]
for i in timedata:
if 'Vibration' in i:
vib=vib.append(i)
to then create a DataFrame based on the indicies of these columns. This really does not seem like the most efficient way to do it and I'm sure there must be something simple to do with list comprehension.
然后根据这些列的索引创建一个 DataFrame。这似乎真的不是最有效的方法,我相信列表理解一定有一些简单的方法。
EDIT
编辑
Dataframe of form:
形式的数据框:
df = DataFrame({'Ch 1:Load': randn(10), 'Ch 2:Vibration Brg 1T ': randn(10), 'Ch 3:Eccentricity Brg 1H ': randn(10), 'Ch 4:Vibration Brg 2T ': randn(10)})
Sorry I'm having a slow day! thanks for any help
抱歉我今天过得很慢!谢谢你的帮助
回答by joris
Something like this to manually select all columns with the word "Vibration" in it:
像这样手动选择所有带有“振动”字样的列:
df[[col for col in df.columns if "Vibration" in col]]
You can also do the same with the filtermethod:
你也可以用这个filter方法做同样的事情:
df.filter(like="Vibration")
If you want to do a more flexible filter, you can use the regexoption. E.g. to look if "Vibration" or "Ecc" is in the column name:
如果你想做一个更灵活的过滤器,你可以使用该regex选项。例如,查看列名中是否包含“Vibration”或“Ecc”:
df.filter(regex='Ecc|Vibration')
回答by Svend Feldt
newDf = Df.loc[:,['Vibration']]
or
或者
newDf = Df.loc[:,['Vibration','eccentricity']]
to get more collumns
获得更多的列
to search for a value in a collumn:
在列中搜索值:
newDf = Df[Df["CollumnName"] == "vibration"]

