我从我的df中提取了列的列表,这些列是字符串类型,如下所示:1999-1(与1999年的第一个月一样)。
我想在2000之前删除所有列,因此我提取列列表并使用列表理解来检查字符串的第一个字符是否为1.
代码运行但我的" columns_to_drop"列表是空的。
def convert_housing_data_to_quarters():
data_source = pd.read_csv('City_Zhvi_AllHomes.csv') #this is the df
data_source['State'] = data_source['State'].map(states)
data_source.drop(['Metro','CountyName','RegionID','SizeRank'],axis=1,inplace=1)
data_source.set_index(['State','RegionName'],inplace=True)
columns = list(data_source.columns)
columns_to_drop = [col for col in columns if col[0]=="1"]
data_source.drop(columns_to_drop,axis=1,inplace=1)
return data_source
convert_housing_data_to_quarters()
答案 0 :(得分:1)
我相信你可以使用:
df = pd.DataFrame(columns=['1999-1','2000-1','2000-10'])
df = df.loc[:, pd.to_datetime(df.columns, format='%Y-%m').year >= 2000]
print (df)
Empty DataFrame
Columns: [2000-1, 2000-10]
Index: []
或者:
df = df.loc[:, df.columns.str[0] != '1']
print (df)
Empty DataFrame
Columns: [2000-1, 2000-10]
Index: []
所有在一起:
def convert_housing_data_to_quarters():
#set index from columns in read csv
data_source = pd.read_csv('City_Zhvi_AllHomes.csv', index_col=['State','RegionName'])
data_source.drop(['Metro','CountyName','RegionID','SizeRank'],axis=1,inplace=True)
data_source = data_source.loc[:, data_source.columns.str[0] != '1']
return data_source
df = convert_housing_data_to_quarters()
print (df.columns)
Index(['2000-01', '2000-02', '2000-03', '2000-04', '2000-05', '2000-06',
'2000-07', '2000-08', '2000-09', '2000-10',
...
'2017-02', '2017-03', '2017-04', '2017-05', '2017-06', '2017-07',
'2017-08', '2017-09', '2017-10', '2017-11'],
dtype='object', length=215)