Fwd: 早间市场快报:中国宣布对600亿美元美国商品征税;俄战机被击落推高油价;欧美股市小幅走高

———- Forwarded message ———
From: 《华尔街日报》中文版 <Editors.Chinese@dowjones.com>
Date: Tue, Sep 18, 2018 at 6:07 PM
Subject: 早间市场快报:中国宣布对600亿美元美国商品征税;俄战机被击落推高油价;欧美股市小幅走高
To: <lgyhz1234@gmail.com>

邮件无法正常显示?查看在线版本

早间市场快报

2018年9月19日

一、热点回顾

中国宣布对美国进行600亿美元关税反击

中国发布意料中的关税反制措施,同时评估是否接受美方继续磋商的提议。中国新一轮关税举措涵盖美国农产品、机械和化学品等,实施日期为9月24日,和美国最新一轮关税同一天生效。中国新加征的关税税率在5%到10%。连同新宣布的关税举措,中国将对总额约1,100亿美元的美国商品加征关税,相当于去年美国输往中国商品的85%。国务院还称,如果美方在明年初进一步将加征关税税率提高至25%,中方也将相应提高上述5-10%的加征关税税率。

中国承诺要稳投资和促进外贸

中国国务院承诺要推出稳住投资及促进外贸增长的措施。国务院常务会议纪要显示,政府必须防止投资大起大落,不能过度依赖投资,也不能不要投资。国务院称,地方政府应该将近期发行债券筹集的资金投入地方项目;此外,鼓励银行确保对这些项目的资金支持。国务院表示,为促进外贸,政府将降低对出口商和进口商的部分通关相关成本。国务院还呼吁金融机构对这类公司提供更多贷款。

俄侦察机被击落加剧地缘政治紧张局势

周二,俄罗斯将侦察机被叙利亚防空系统击落一事归咎于以色列,这加剧了以俄之间的紧张关系。据俄罗斯国际文传电讯社报道,俄罗斯国防部发言人称,这架前苏联设计的伊尔-20飞机被叙利亚老旧的S-200防空系统击落,致15名俄罗斯军人死亡。之后,以色列军方证实了此事,但将飞机被击落归咎于阿萨德政权。

二、隔夜金融市场回顾

美股上涨,未理会新一轮关税举措影响;欧洲股市也微幅收高;美元则从关税引发的跌势中反弹走高;美国国债抛售加剧,10年期国债收益率升破3%;受俄战机被击落加剧地缘政治紧张局势的影响,油价走高;美国新关税税率不及预期提振铜价大涨;金价小幅下跌。中国周二宣布反击措施,对600亿美元美国商品加征关税。

——外汇市场

纽约汇市周二后市,美元走高,盘中早些时候受中国宣布的新关税举措影响美元一度下跌。ICE美元指数涨0.2%,至94.664。美中贸易战升级。特朗普周一表示,美国将对价值约2000亿美元中国进口商品征收10%关税,并威胁将再把价值数百亿美元的商品纳入关税清单。北京方面宣布采取报复性措施,将对价值600亿美元的美国进口商品加征关税。其他主要货币方面,欧元兑美元尾盘报1.1663美元,周一尾盘报1.1685美元;美元兑日圆涨0.5%,至112.38日圆,为7月中以来最高。

——股票市场

美国股市周二上涨,因为投资者认为美国针对中国进口商品推出的新一轮关税举措以及中国的初步反应比预期温和。道指涨184.84点,涨幅0.7%,至26246.96点;标普500指数涨15.51点,涨幅0.5%,至2904.31点;纳指涨60.32点,涨幅0.8%,至7956.11点。一些交易员称,由于最新一轮关税的实施时间将是交错的,投资者对美中两国之间仍有时间来谈判持谨慎乐观态度。科技类股受到的关税影响并不像担心的那样严重。标普500指数中的科技类股在周一下跌1.4%之后,周二反弹0.6%。

欧洲主要股指周二挣扎于突破窄幅波动区间,受到美中贸易战升级的拖累。德国零售商Zalando SE跌幅居前,瑞士化学品公司Clariant AG SA大涨。欧洲斯托克600指数上涨0.1%,至378.73点。该股周一小涨0.1%。德国DAX 30指数上涨0.5%,至12157.67点。法国CAC 40指数上涨0.3%,至5363.79点。英国富时100指数大致持平,微跌至7300.23点。纽约市场,欧元兑美元报1.1691美元,周一晚报1.1685美元。

——美国国债

持续数周的美国国债抛售周二加剧,10年期国债收益率升破3%,而该收益率数月来一直未能突破这一水平。基准10年期国债收益率收报3.048%,为5月22日以来的最高水平,周一报3.001%。国债收益率起初下跌,之后追随全球股市攀升,此前特朗普政府于周一晚间宣布从9月24日起对中国进口商品加征关税。国债收益率周二继续上涨,反映出投资者对风险资产的需求,尽管中国政府已表示将对600亿美元美国进口商品加征关税予以反击。

——商品市场

原油期货周二走高,受到地缘政治紧张局势加剧的提振,此前俄罗斯指责以色列造成前夜一架俄罗斯侦察机被叙利亚防御系统击落。纽约商业交易所十月交割的轻质低硫原油期货上涨1.4%至每桶69.85美元。布伦特原油期货上涨1.3%至每桶79.03美元。俄罗斯侦察机被叙利亚防御系统击落,可能增加地缘政治的不稳定性,造成全球原油市场的不确定性。

铜期货周二收盘反弹,因美国和中国宣布的新一轮关税举措不及一些投资者此前担忧得那么严重。纽约商交所九月份交割的铜期货结算价上涨3%,至2.712美元/磅,缔造该期货自4月18日以来最大单日涨幅。一些分析师表示,美国从9月24日起对中国进口商品加征10%关税的举措比预期较为克制。一些分析师此前预期美国将加征25%的关税,但特朗普政府表示,新关税只会在今年年底调高到25%。

九月份交割的黄金期货结算价小幅下跌0.2%,至1196.8美元/盎司。

三、今日市场展望

经济事件预告

日本 8月份贸易余额、日本央行货币政策委员会会议决定

新西兰 第二季度经常项目

澳大利亚 8月份空置报告

欧盟 欧元区经济前景、7月份贸易余额

英国 8月份消费者价格指数、8月份生产者价格指数、英国 7月份房屋价格

意大利 7月份经常项目

美国 第二季度经常项目、新屋开工及建筑许可

四、深度/独家报道

美国贸易战反助中国制造业升级

美国白宫对中国发动的贸易战带来了一个意想不到的后果:在中国制造业中心珠江三角洲,为了同美国商品一争高下,企业正在加快升级步伐,提高产品质量。

LTS Group是一家生产灯具和其他照明产品的企业,其商品在美国门店销售。面对关税带来的产品价格上升,LTS Group的Michael Lu计划在他的工厂里增添更多机器人来降低成本。他还着手将技术含量较低的生产转移到亚洲其他地方。

他的研发业务将留在深圳,负责生产智能照明设备等更复杂的产品的熟练工人团队也将留在深圳。

在他的深圳工厂里,身穿红色制服的工人正在组装台灯,Lu说:“美国的关税行动正在促使中国转向更高端产品的生产,未来将帮助中国提升竞争力。”

从袜子到玩具再到钢铁,中国靠着大量出口廉价商品构筑起了经济大厦,现在开始致力于制造业升级。过去几年,中国政府开始将低技术生产转至其他国家,着力打造使用先进技术生产高价值产品的经济模式。

美国加征关税将打击海外企业向美国消费者销售廉价产品的利润,迫使企业反思自己的业务模式和产品,与此同时,中国政府也在提供更多激励措施,帮助企业实现转型。

加速这一进程并非美国总统特朗普(Trump)实施关税的目的。美国的关税行动旨在阻止美国政府所谓的不公平竞争,美方称,中国对芯片等战略产业的扶持政策有失公平,中国还利用工业间谍等手段获取美国汽车企业和其他公司的商业机密。

小型股或推动美股继续走高

今年美国股市涨势主要归功于科技巨头,但小型公司不动声色的强劲表现是继续押注美国股市的一个理由。

投资者和分析人士表示,股市大范围走强的迹象随处可见:今年以来,小型股的涨幅已超过大型股。如果赋予标普500指数中所有成分公司同等权重,该指数也仍接近纪录水平。与此同时,今年上涨的股票数量超过了下跌股数。

与此同时,强劲的利润增长令2018年初投资者感到担忧的高估值出现降温趋势。

投资者表示,即使亚马逊公司(Amazon.com Inc. ,AMZN)、谷歌(Google)母公司Alphabet Inc.(GOOG)和Netflix Inc. (NFLX)等知名公司的表现欠佳,上述因素对股市来说也是好兆头。继进入牛市九年多之后,许多投资者都在提防低迷迹象。颇受欢迎的科技股今夏出现动荡之势再加上新兴市场近期的下跌,引发了投资者对牛市终结的担忧,但到目前为止美国股市似乎表现出了韧性。

当前市场上不动声色的赢家是中型企业。根据Strategas Securities LLC的数据,当基于市场价值高低将罗素1000指数成分股划分五类时,第二、三类成分股的表现要好于第一类大型成分股。Strategas的数据显示,今年第二、三类成分股股价已分别上涨13%和12%,超过第一类成分股的8.7%涨幅。

编辑:孙海琴 haiqin.sun@dowjones.com

关注我们

扫码订阅道琼斯中文财经资讯电邮

本栏目文字内容归道琼斯公司所有, 任何单位及个人未经许可, 不得擅自转载使用。

Copyright 2018 Dow Jones & Company, Inc. All Rights Reserved.

Pandas — Data Overviewing, Slicing and Selection




Untitled







Data Overview, Slicing and Selection

In [1]:
import pandas as pd
In [2]:
stock_data = pd.read_csv("pair_ETF_0302.csv")

When you read from raw data file, you get a Dataframe.

In [3]:
type(stock_data)
Out[3]:
pandas.core.frame.DataFrame

Data Overview

Get an overview of the data that you are working on. In this stage, you will focus on getting a board idea of data size, data type and information.

In [4]:
stock_data.head() #This is a function call, remember the ()
Out[4]:
pairs ave_return total_return volatility sharp_ratio
0 (‘NYT’, ‘BANC’) -1683.602874 -15.167593 139.660600 -0.108603
1 (‘EEA’, ‘ESS’) 7.915179 0.121772 123.131991 0.000989
2 (‘BXP’, ‘LFC’) 1194.149695 11.593686 88.070115 0.131642
3 (‘PCF’, ‘ANIK’) 2.441353 0.021605 13.484533 0.001602
4 (‘NDSN’, ‘POL’) -293.861701 -3.719768 36.593718 -0.101650
In [5]:
stock_data.tail()
Out[5]:
pairs ave_return total_return volatility sharp_ratio
58587 (‘INFO’, ‘MYF’) 1111.644206 8.964873 84.062452 0.106645
58588 (‘AL’, ‘CSL’) 917.521116 7.399364 63.715749 0.116131
58589 (‘PFL’, ‘DSW’) -876.763054 -7.070670 49.698238 -0.142272
58590 (‘HWBK’, ‘KRNY’) -106.253729 -0.856885 22.987587 -0.037276
58591 (‘AN’, ‘KAP’) 36.888918 0.297491 7.444777 0.039960

You can access columns the below methods

In [6]:
stock_data.pairs.head()
Out[6]:
0    ('NYT', 'BANC')
1     ('EEA', 'ESS')
2     ('BXP', 'LFC')
3    ('PCF', 'ANIK')
4    ('NDSN', 'POL')
Name: pairs, dtype: object
In [7]:
stock_data["pairs"].head()
Out[7]:
0    ('NYT', 'BANC')
1     ('EEA', 'ESS')
2     ('BXP', 'LFC')
3    ('PCF', 'ANIK')
4    ('NDSN', 'POL')
Name: pairs, dtype: object

You will get a data type of Series. You can view Series as a single unit of Dataframe.

In [8]:
type(stock_data["pairs"])
Out[8]:
pandas.core.series.Series

You can access specific cell like this.

In [9]:
stock_data["pairs"][0]
Out[9]:
"('NYT', 'BANC')"
In [10]:
type(stock_data["pairs"][0])
Out[10]:
str

Slicing and Selection

You can access a certain portion of data. Please remind that index starts from 0.

In [11]:
stock_data[:].head() #Showing all slices
Out[11]:
pairs ave_return total_return volatility sharp_ratio
0 (‘NYT’, ‘BANC’) -1683.602874 -15.167593 139.660600 -0.108603
1 (‘EEA’, ‘ESS’) 7.915179 0.121772 123.131991 0.000989
2 (‘BXP’, ‘LFC’) 1194.149695 11.593686 88.070115 0.131642
3 (‘PCF’, ‘ANIK’) 2.441353 0.021605 13.484533 0.001602
4 (‘NDSN’, ‘POL’) -293.861701 -3.719768 36.593718 -0.101650
In [12]:
stock_data[2:].head()  #start from the 3rd row
Out[12]:
pairs ave_return total_return volatility sharp_ratio
2 (‘BXP’, ‘LFC’) 1194.149695 11.593686 88.070115 0.131642
3 (‘PCF’, ‘ANIK’) 2.441353 0.021605 13.484533 0.001602
4 (‘NDSN’, ‘POL’) -293.861701 -3.719768 36.593718 -0.101650
5 (‘DAKT’, ‘LPG’) -578.896261 -5.122976 255.150999 -0.020078
6 (‘AGR’, ‘MXIM’) 2203.294225 21.600924 163.622809 0.132017
In [13]:
stock_data[:3] #get until the 4th row
Out[13]:
pairs ave_return total_return volatility sharp_ratio
0 (‘NYT’, ‘BANC’) -1683.602874 -15.167593 139.660600 -0.108603
1 (‘EEA’, ‘ESS’) 7.915179 0.121772 123.131991 0.000989
2 (‘BXP’, ‘LFC’) 1194.149695 11.593686 88.070115 0.131642
In [14]:
stock_data["pairs"].head()  # Usually I use column name to access column
Out[14]:
0    ('NYT', 'BANC')
1     ('EEA', 'ESS')
2     ('BXP', 'LFC')
3    ('PCF', 'ANIK')
4    ('NDSN', 'POL')
Name: pairs, dtype: object

More Slicing and Selection

This doesn’t work because it’s accessing the index, and the Dataframe doesn’t have the index named 0

In [15]:
stock_data[0] 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-15-e3654389130b> in <module>()
----> 1 stock_data[0]

C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2683             return self._getitem_multilevel(key)
   2684         else:
-> 2685             return self._getitem_column(key)
   2686 
   2687     def _getitem_column(self, key):

C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\frame.py in _getitem_column(self, key)
   2690         # get column
   2691         if self.columns.is_unique:
-> 2692             return self._get_item_cache(key)
   2693 
   2694         # duplicate columns & possible reduce dimensionality

C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\generic.py in _get_item_cache(self, item)
   2484         res = cache.get(item)
   2485         if res is None:
-> 2486             values = self._data.get(item)
   2487             res = self._box_item_values(item, values)
   2488             cache[item] = res

C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\internals.py in get(self, item, fastpath)
   4113 
   4114             if not isna(item):
-> 4115                 loc = self.items.get_loc(item)
   4116             else:
   4117                 indexer = np.arange(len(self.items))[isna(self.items)]

C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3063                 return self._engine.get_loc(key)
   3064             except KeyError:
-> 3065                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   3066 
   3067         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0
In [16]:
stock_data.iloc[0] #But you can access nth row using .iloc[n]
Out[16]:
pairs           ('NYT', 'BANC')
ave_return              -1683.6
total_return           -15.1676
volatility              139.661
sharp_ratio           -0.108603
Name: 0, dtype: object
In [17]:
type(stock_data.iloc[0]) #it returns a Series
Out[17]:
pandas.core.series.Series
In [18]:
stock_data.iloc[0:2] #You can also feed a portion to .iloc and it will return Dataframe
Out[18]:
pairs ave_return total_return volatility sharp_ratio
0 (‘NYT’, ‘BANC’) -1683.602874 -15.167593 139.660600 -0.108603
1 (‘EEA’, ‘ESS’) 7.915179 0.121772 123.131991 0.000989
In [19]:
stock_data.loc[[1,2]] #.loc can also be feeded a list of index
Out[19]:
pairs ave_return total_return volatility sharp_ratio
1 (‘EEA’, ‘ESS’) 7.915179 0.121772 123.131991 0.000989
2 (‘BXP’, ‘LFC’) 1194.149695 11.593686 88.070115 0.131642

Using .loc[], you can conduct more complex selection

In [20]:
stock_data.loc[:,"pairs"].head() # .loc can also be used to access columns 
Out[20]:
0    ('NYT', 'BANC')
1     ('EEA', 'ESS')
2     ('BXP', 'LFC')
3    ('PCF', 'ANIK')
4    ('NDSN', 'POL')
Name: pairs, dtype: object

Remember to feed a list when you want to select multiple columns or rows

In [21]:
stock_data.loc[:,["pairs","total_return"]].head()
Out[21]:
pairs total_return
0 (‘NYT’, ‘BANC’) -15.167593
1 (‘EEA’, ‘ESS’) 0.121772
2 (‘BXP’, ‘LFC’) 11.593686
3 (‘PCF’, ‘ANIK’) 0.021605
4 (‘NDSN’, ‘POL’) -3.719768
In [22]:
stock_data.loc[stock_data["ave_return"]>0].head()
Out[22]:
pairs ave_return total_return volatility sharp_ratio
1 (‘EEA’, ‘ESS’) 7.915179 0.121772 123.131991 0.000989
2 (‘BXP’, ‘LFC’) 1194.149695 11.593686 88.070115 0.131642
3 (‘PCF’, ‘ANIK’) 2.441353 0.021605 13.484533 0.001602
6 (‘AGR’, ‘MXIM’) 2203.294225 21.600924 163.622809 0.132017
8 (‘PUK’, ‘UTX’) 184.141559 1.629571 28.527874 0.057122

.loc is for index access, which means you should feed index or index generator into .iloc[]

In [23]:
stock_data.loc[[True,True,False]] #Boolean can be feeded into .loc, empty means false
Out[23]:
pairs ave_return total_return volatility sharp_ratio
0 (‘NYT’, ‘BANC’) -1683.602874 -15.167593 139.660600 -0.108603
1 (‘EEA’, ‘ESS’) 7.915179 0.121772 123.131991 0.000989

To use more complex selection, you can use lambda functions

In [24]:
stock_data.loc[lambda stock_data:stock_data["total_return"]>200000]
Out[24]:
pairs ave_return total_return volatility sharp_ratio
4684 (‘ITG’, ‘OIS’) inf inf NaN NaN
12016 (‘LEA’, ‘CTX’) 1.873543e+08 1.510922e+06 1.684723e+07 0.089684
24034 (‘ENVA’, ‘CTX’) 1.718711e+08 1.386057e+06 1.537679e+07 0.090140
34122 (‘TVPT’, ‘FULT’) inf inf NaN NaN
42235 (‘FOE’, ‘AOD’) inf inf NaN NaN
42749 (‘ALTR’, ‘EPD’) inf inf NaN NaN
46295 (‘FORM’, ‘AMSF’) inf inf NaN NaN
46678 (‘GS’, ‘ONB’) inf inf NaN NaN
54771 (‘NOV’, ‘CTX’) 1.789989e+08 1.443540e+06 1.601276e+07 0.090149

One Last Thing

As a good practice, you should always use .loc to set value. Because if you use direct access, like stock_data[“pairs”], Python will return a copy of the Dataframe, which is not changeable.

In [25]:
stock_data.loc[0,"ave_return"] = 0
In [26]:
stock_data.head()
Out[26]:
pairs ave_return total_return volatility sharp_ratio
0 (‘NYT’, ‘BANC’) 0.000000 -15.167593 139.660600 -0.108603
1 (‘EEA’, ‘ESS’) 7.915179 0.121772 123.131991 0.000989
2 (‘BXP’, ‘LFC’) 1194.149695 11.593686 88.070115 0.131642
3 (‘PCF’, ‘ANIK’) 2.441353 0.021605 13.484533 0.001602
4 (‘NDSN’, ‘POL’) -293.861701 -3.719768 36.593718 -0.101650

Series & Numpy Array

Pandas’s Series is internally Numpy Array. In the following demonstration, you will see if you take .values of the Series, you get an array.

In [30]:
stock_data.head()["pairs"].values
Out[30]:
array(["('NYT', 'BANC')", "('EEA', 'ESS')", "('BXP', 'LFC')",
       "('PCF', 'ANIK')", "('NDSN', 'POL')"], dtype=object)

Pandas — Reading Raw Data

Pandas is a powerful data organization and analysis toolbox in Python. It has functions and methods that can help you clean, organize and present data in much nicer way than any other data structures.

I will not be able to cover all Pandas functions/methods, but I would rather try to discover the logic and methodology underneath this package. So, you don’t need to remember everything but still be able to get things done efficiently.

First of all, I will talk about reading raw data from various sources using Pandas.

As you can see below, using pd.read_xxx, you can read various data file into Pandas.

Let’s take a close look at read_csv, which is the most common raw data file type.

One trick to get a first look at a method/function that you are using is to press TAB button, and it will show you all the available options.

 

Usually, you can just feed the file path to read the file.

But sometimes, you got broken data frame, and those reading options can help you get a better result.

Choosing The Right Python Data Type for Analysis


Untitled






In [4]:
import datetime 

Dictionary

Dictionary is used when there exists a mapping relationship, for example, in stock market data, stock prices are linked to a specific date.

In [94]:
stock = {"Header":["Open","High","Low","Close"],"12/12/2015":[32.03,50,40,32]}
In [95]:
stock["12/12/2015"]
Out[95]:
[32.03, 50, 40, 32]

Dictionary provides some useful methods

In [74]:
list(stock.iterkeys())  #key iterator, giving you a list
Out[74]:
['Header', '12/12/2015']
In [78]:
list(stock.iteritems()) #iterm iterator, giving you tuples, representing relations
Out[78]:
[('Header', ['Open', 'High', 'Low', 'Close']),
 ('12/12/2015', [32.03, 50, 40, 32])]

Dictionary can also be feeded in the constructor of pandas dataframe. We will talk about this in my later posts.

Tuple

Anything you want to be considered as a whole should use turple becuase it’s immutable. Turple often used in feeding a set of arguments into function caller.

In [68]:
x=12
y=23
z=23.6

point = (x,y,z) # a coordinate can use turple to replesent because the
                # position of each element matters 

Some people also argues that you can compare tuple to strcut in C/C++ since tuple usually holds heterogeneous collections.

As I mentioned, tuple also used to represent relations in discrete data structure. I can use you an example using dictionary and tuple

In [66]:
# for example, we have y = x^2
f = {1:1,2:4,3:9}
f.items()  # the items method can turn dictionary into a tuple
Out[66]:
[(1, 1), (2, 4), (3, 9)]

List

List is like array in other programming language. You should use list in situations that uses array. In python, list provides you more methods to perform comprehensive analysis.

List as stack operation

In [14]:
l = []
l.append(1)
l.append(2)
l.append(3)
In [15]:
l
Out[15]:
[1, 2, 3]
In [22]:
l.pop()  # First in first out 
Out[22]:
1
In [17]:
l
Out[17]:
[1, 2]
In [18]:
l.append(4)
l
Out[18]:
[1, 2, 4]
In [19]:
l.pop()
Out[19]:
4
In [20]:
l.pop()
Out[20]:
2
In [21]:
l
Out[21]:
[1]

List sorting

In [32]:
l = [2,3,9,4]
l.sort()
In [33]:
l
Out[33]:
[2, 3, 4, 9]

List Reversing

In [34]:
l.reverse()
In [35]:
l
Out[35]:
[9, 4, 3, 2]

List Extend Method

In [40]:
l.extend([1]) # need to feed a list, and will insert the element to a proper place
In [39]:
l
Out[39]:
[9, 4, 3, 2, 1]

Other List Methods

In [42]:
l.remove(1) #remove elements
l
Out[42]:
[9, 4, 3, 2]
In [52]:
l.index(4) # return the position of an element
Out[52]:
1
In [62]:
l.insert(0,2) # insert 2 into index 0
l
Out[62]:
[2, 9, 4, 3, 2]

We will talk about data structure usage more in-depth later in my blog when we go further into analysis.

Python Basic Data Structure — Set




Set







A set in python is the same concept of the set in Discret Math. A set contains unique unorder elements.

In python, a set is definded by putting “{}”

In [2]:
s = {1,2,3}
s
Out[2]:
{1, 2, 3}
In [5]:
s = {"1231",(1,2,3),2} # A set can contain different data type

A set is nonordered, so it can not access by indexing

In [7]:
s[0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-4e98c4f87897> in <module>()
----> 1 s[0]

TypeError: 'set' object does not support indexing

However, it can be access by iterating

In [6]:
for ele in s:
    print ele
2
1231
(1, 2, 3)

If feeding a set with same elements, it will only save that element once, for example,

In [12]:
s_1 = {1,1,(1,2),(1,2)}
s_1
Out[12]:
{1, (1, 2)}

You can turn other data strcture in python into a set by using set() function

In [15]:
l = [1,2,3,3,2]
t = (2,2,2,1)
set(l)
Out[15]:
{1, 2, 3}
In [16]:
set(t)
Out[16]:
{1, 2}

Python Basic Data Structure — Tuple




Tuple







First of all, a tuple is defined by putting “()”, and using “,” to seperate values. Turple is sequencial, meaning the ordering matters.

In [3]:
t=(1,2,3)
t
Out[3]:
(1, 2, 3)

Same as list or ditionary, tuple can hold values of different type

In [4]:
t=("1",2.0,3)
t
Out[4]:
('1', 2.0, 3)
In [5]:
t[0]  #accessing tuple value is the same as list
Out[5]:
'1'

However, you can not alter element in tuple because tuple is considered, because turple is considered immutable. In discrete math, turple usually represent functions and directional object.

In [6]:
t[0]=2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-0c0cc230f53e> in <module>()
----> 1 t[0]=2

TypeError: 'tuple' object does not support item assignment

One thing needs to pay attention is when you want to assign a singlton, you need to leave a comma, for example,

In [15]:
t2=(2)   # this won't give you a turple
t2  
Out[15]:
2
In [16]:
type(t2)
Out[16]:
int
In [17]:
t3=(2,)  # you have to leave a comma
t3
Out[17]:
(2,)
In [19]:
type(t3)
Out[19]:
tuple

Python Basic Data Structure — Dictionary




Dictionary







In this part, we will show examples of dictionary. Dictionary provides a way for you to map a specific value to another one.

In [2]:
my_dict = {"1":1,"2":2}
print my_dict
{'1': 1, '2': 2}

Different than list, dictionary require the get method for its elements

In [4]:
my_dict.get("1")
Out[4]:
1
In [20]:
my_dict.update({"1":2})

You can use copy method to define a new dictionary

In [21]:
new_dict = my_dict.copy()
print new_dict
{'1': 2, '2': 2}

You can use iterkeys method to get the iternerator of keys, and wrap a list function to get the list value.

In [22]:
print (list(new_dict.iterkeys()))

print (list(new_dict.itervalues()))
['1', '2']
[2, 2]
In [30]:
new_dict["3"] =3
print new_dict
{'1': 2, '3': 3, '2': 2}

Python Basic Data Structure– List

List

List is the most common type of handling data

In [2]:
#generate list of 0 to 9 
my_list = range(10)
In [3]:
my_list
Out[3]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

As you can see, list is braced by [ ]

In [4]:
# You can retrive list element
my_list[0]
Out[4]:
0

List can hold different data types

In [5]:
# To add something into a list, use append methon
# This methond can only append one element at a time
my_list.append("1")
In [6]:
my_list
Out[6]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '1']
In [7]:
# You can also store a list in a list
my_list.append(["1",1.2032,0x2f2])
In [8]:
# when you print the list hexedecimal number will be converted to decimal
my_list
Out[8]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '1', ['1', 1.2032, 754]]

List Indexing

In [9]:
# remember index starts with 0
print (my_list[0])
print (my_list[11])
# You can also count backward, and it starts with -1
print (my_list[-1])
0
['1', 1.2032, 754]
['1', 1.2032, 754]

List Slicing

In [10]:
start_position = 0
end_position = 10

my_list[start_position:end_position]
Out[10]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [11]:
start_position = 2
end_position = 3

my_list[start_position:end_position]
Out[11]:
[2]
In [12]:
start_position = -5
end_position = -1

my_list[start_position:end_position]
Out[12]:
[7, 8, 9, '1']

Just pay attention to these 3 examples. When doing list slicing, you are not pointing element, but slicing between elements. That's why my_list[2:3] gives you the second element.

Fwd: Share about saving energy.

———- Forwarded message ——— From: Daily Challenge <meyouhealth+2lwbros11qjtn@incoming.meyouhealth.com> Date: Mon, Sep 17, 2018 at 7:35 AM Subject: Share about saving energy. To: <lgyhz1234@gmail.com>

Share 1 way that you save energy in your home or at work. DONE <challenge.meyouhealth.com/cl/8ea4213e-ac7d-4f24-852b-2e51c1ca0b3d?escape=false&h=e707a36c&p=U2FsdGVkX1%2FwdDJIQdE42O5bpN6Gs2kmWQ0PYEPZ9Bq6tka7ec0XP2c6U0gct%2FzV5wA65G5N7yhFnTGAonKXNLD8iFw7UgafLFaUt…>

How to do it
Do you shut off the lights as soon as you leave a room? Switch off your computer at the end of a workday? Wash your clothing in the coolest water possible? Whatever your method for saving energy, share it here.
Why it matters
The benefits of saving energy are numerous! Taking time to conserve means less contamination of our planet’s land, water, and air. Using less fossil fuel also reduces the carbon emissions that contribute to global warming. Finally, saving energy leads to lower utility bills, meaning more money for you.

Yesterday, *3926 people* posted about their challenge.

Download our handy app and get your challenges on the go.
[image: Download from App Store] <challenge.meyouhealth.com/gc/challenge-mailer-ios> [image: Download from Google Play Store] <challenge.meyouhealth.com/gc/challenge-mailer-android>

You can change your subscription settings <challenge.meyouhealth.com/cl/8ea4213e-ac7d-4f24-852b-2e51c1ca0b3d?escape=false&h=831ee47e&p=U2FsdGVkX19ICj4I3DhydN5cTYFNzLSEYBqbK20xYrI92ugMZqRd3TLBqpo3NZbzWuK25yVxwpog%2FnrcM0i0diCP9gYVTzyUsmqoFrk…> any time.
MeYou Health does not provide medical advice, diagnosis, or treatment.
© 2018 MYH, Inc. All rights reserved.
Terms of Use <challenge.meyouhealth.com/agreement> | Privacy Policy <challenge.meyouhealth.com/privacy> | Support <challenge.meyouhealth.com/help>