美文网首页
2019-10-28

2019-10-28

作者: 数据小黑升值记 | 来源:发表于2019-10-28 20:30 被阅读0次
  • 从 DataFrame 到 Excel
  • 从 Excel 到 DataFrame
  • 从 DataFrame 到 JSON
  • 从 JSON 到 DataFrame
import pandas as pd
import sys
print('Python version ' + sys.version)
print('Pandas version ' + pd.__version__)
Python version 3.6.1 | packaged by conda-forge | (default, Mar 23 2017, 21:57:00) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)]
Pandas version 0.19.2

从 DataFrame 到 Excel

# 创建一个 DataFrame
d = [1,2,3,4,5,6,7,8,9]
df = pd.DataFrame(d, columns = ['Number'])
df

<div>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1</td>
</tr>
<tr>
<th>1</th>
<td>2</td>
</tr>
<tr>
<th>2</th>
<td>3</td>
</tr>
<tr>
<th>3</th>
<td>4</td>
</tr>
<tr>
<th>4</th>
<td>5</td>
</tr>
<tr>
<th>5</th>
<td>6</td>
</tr>
<tr>
<th>6</th>
<td>7</td>
</tr>
<tr>
<th>7</th>
<td>8</td>
</tr>
<tr>
<th>8</th>
<td>9</td>
</tr>
</tbody>
</table>
</div>

# 导出到 Excel
df.to_excel('./Lesson10.xlsx', sheet_name = 'testing', index = False)
print('Done')
Done

从 Excel 到 DataFrame

# Excel 文件的路径
# 按照你的要求修改文件路径
location = r'./Lesson10.xlsx'

# 读入 Excel 文件
df = pd.read_excel(location, 0)
df.head()

<div>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1</td>
</tr>
<tr>
<th>1</th>
<td>2</td>
</tr>
<tr>
<th>2</th>
<td>3</td>
</tr>
<tr>
<th>3</th>
<td>4</td>
</tr>
<tr>
<th>4</th>
<td>5</td>
</tr>
</tbody>
</table>
</div>

df.dtypes
Number    int64
dtype: object
df.tail()

<div>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<th>4</th>
<td>5</td>
</tr>
<tr>
<th>5</th>
<td>6</td>
</tr>
<tr>
<th>6</th>
<td>7</td>
</tr>
<tr>
<th>7</th>
<td>8</td>
</tr>
<tr>
<th>8</th>
<td>9</td>
</tr>
</tbody>
</table>
</div>

从 DataFrame 到 JSON

df.to_json('Lesson10.json')
print('Done')
Done

从 JSON 到 DataFrame

# 按照你的要求修改文件路径
jsonloc = r'./Lesson10.json'

# read json file
df2 = pd.read_json(jsonloc)
df2

<div>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1</td>
</tr>
<tr>
<th>1</th>
<td>2</td>
</tr>
<tr>
<th>2</th>
<td>3</td>
</tr>
<tr>
<th>3</th>
<td>4</td>
</tr>
<tr>
<th>4</th>
<td>5</td>
</tr>
<tr>
<th>5</th>
<td>6</td>
</tr>
<tr>
<th>6</th>
<td>7</td>
</tr>
<tr>
<th>7</th>
<td>8</td>
</tr>
<tr>
<th>8</th>
<td>9</td>
</tr>
</tbody>
</table>
</div>

df2.dtypes
Number    int64
dtype: object

相关文章

网友评论

      本文标题:2019-10-28

      本文链接:https://www.haomeiwen.com/subject/slhivctx.html