我使用get()
python模块中的Quandl
函数从Quandl下载了一个时间序列,并调用了UNES_HARD_COAL_BR
,它的形状为(24,19)
,但我想只使用第1列到第3列和第18列。我使用名为ll
的列表并在drop()
对象中应用DataFrame
方法编写此脚本来完成此工作,该列表包含我不使用的列名称。 这里的挑战是不创建列表。
import Quandl
import pandas as pd
UNES_HARD_COAL_BR = Quandl.get("UENG/CL_BRA", authtoken="xX6ntNSFuvq7eCZvDdvL")
UNES_HARD_COAL_BR.columns = UNES_HARD_COAL_BR.columns.str.replace(' ', '_')
ll =['Hard_coal_-_transformation_(Metric_tons,_thousand)', 'Hard_coal_-_transformation_in_coke_ovens_(Metric_tons,_thousand)','Hard_coal_-_transformation_in_electricity,_CHP_and_heat_plants_(Metric_tons,_thousand)','Hard_coal_-_transformation_in_electricity_plants_-_main_activity_producers_(Metric_tons,_thousand)','Hard_coal_-_final_energy_consumption_(Metric_tons,_thousand)','Hard_coal_-_consumption_by_manufacturing,_construction_and_non-fuel_mining_industry_(Metric_tons,_thousand)','Hard_coal_-_consumption_by_other_manuf.,_const._and_non-fuel_ind._(Metric_tons,_thousand)','Hard_coal_-_final_consumption_(Metric_tons,_thousand)','Hard_coal_-_stock_changes_(Metric_tons,_thousand)','Hard_coal_-_transformation_in_electricity_plants_-_autoproducers_(Metric_tons,_thousand)','Hard_coal_-_consumption_by_transport_(Metric_tons,_thousand)','Hard_coal_-_consumption_by_rail_(Metric_tons,_thousand)','Hrad_coal_-_consumption_by_iron_and_steel_industry_(Metric_tons,_thousand)', 'Hard_coal_-_losses_(Metric_tons,_thousand)', 'Hard_coal_-_total_energy_supply_(Metric_tons,_thousand)']
UNES_HARD_COAL_BR.drop(ll, axis=1, inplace=True)
How to select only specific columns from a DataFrame with MultiIndex columns?
pandas: Extracting specific selected columns from a DataFrame to new DataFrame
答案 0 :(得分:1)
使用.iloc[]
并注意pandas会计算从0
开始的列:
In [14]: UNES_HARD_COAL_BR = UNES_HARD_COAL_BR.iloc[:, [0,1,2,17]]
In [15]: UNES_HARD_COAL_BR.head()
Out[15]:
Hard_coal_-_production_(Metric_tons,_thousand) \
Date
1990-12-31 4595.0
1991-12-31 5188.0
1992-12-31 4731.0
1993-12-31 4595.0
1994-12-31 5134.0
Hard_coal_-_imports_(Metric_tons,_thousand) \
Date
1990-12-31 10146.0
1991-12-31 10758.0
1992-12-31 10399.0
1993-12-31 10975.0
1994-12-31 11319.0
Hard_coal_-_exports_(Metric_tons,_thousand) \
Date
1990-12-31 NaN
1991-12-31 NaN
1992-12-31 NaN
1993-12-31 NaN
1994-12-31 NaN
Hard_coal_-_consumption_by_chemical_and_petrochemical_industry_(Metric_tons,_thousand)
Date
1990-12-31 260.0
1991-12-31 375.0
1992-12-31 390.0
1993-12-31 362.0
1994-12-31 354.0