9

I have a pandas DataFrame called timedata with 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?

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.

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

2 Answers 2

25

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 filter method:

df.filter(like="Vibration")

If you want to do a more flexible filter, you can use the regex option. E.g. to look if "Vibration" or "Ecc" is in the column name:

df.filter(regex='Ecc|Vibration')
3
  • 1
    filter works perfectly for what I need. Thanks alot. Sorry I can't upvote because my rep is too low Jan 3, 2014 at 12:24
  • is it possible to do something like df.filter(like='Ecc' or 'Vibration')? I tried this and it didnt work Jan 3, 2014 at 12:44
  • 2
    Added the regex option?
    – joris
    Jan 3, 2014 at 12:52
2
 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"]    
4
  • Sorry, I didn't make myself clear, the Column names do not just include the word 'Vibration'. e.g. they are in the form 'Ch 2: Vibration Brg 6T' Jan 3, 2014 at 12:04
  • I get the error KeyError: "[['Vibration']] are not in ALL in the [columns]". Thanks for the quick reply though Jan 3, 2014 at 12:04
  • Updated my answer, to what I think you need. Please update your original post to show your DataFrame layout. Jan 3, 2014 at 12:12
  • Have added to the answer, hope this explains it better Jan 3, 2014 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.