Delete column of data frame if column name ends with some row, Python 3.6

I have a dataframe with below columns:

SectorName', 'Sector', 'ItemName', 'Item', 'Counterpart SectorName', 'Counterpart Sector', 'Stocks and TransactionsName', 'Stocks and Transactions', 'Units', 'Scale', 'Frequency', 'Date', 'Value'

How to remove a column from dfwhere the column name ends with Name.

+4
source share
1 answer

You can filter by inverting (~) the logical mask for columns that do not need to be removed with locand str.endswithalso works str.containswith $for the end of the line end:

cols = ['SectorName', 'Name Sector', 'ItemName', 'Item', 'Counterpart SectorName']
df = pd.DataFrame([range(5)], columns = cols)
print (df)
   SectorName  Name Sector  ItemName  Item  Counterpart SectorName
0           0            1         2     3                       4

print (~df.columns.str.endswith('Name'))
[False  True False  True False]

df1 = df.loc[:, ~df.columns.str.endswith('Name')]

df1 = df.loc[:, ~df.columns.str.contains('Name$')]

Or first write down the column names:

print (df.columns[~df.columns.str.endswith('Name')])
Index(['Sector', 'Item'], dtype='object')

df1 = df[df.columns[~df.columns.str.endswith('Name')]]

print (df1)
   Name Sector  Item
0            1     3
+4
source

Source: https://habr.com/ru/post/1686139/


All Articles