import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],
columns=['one', 'two', 'three'])#创建一个数据表格
df['four'] = 'bar'#加入新的一列
df['five'] = df['one'] > 0#加入新的一列,通过判断数据大小加入bool型列
df['six'] = 'ball'
df
one | two | three | four | five | six | |
---|---|---|---|---|---|---|
a | -0.789719 | 0.821745 | 0.441262 | bar | False | ball |
c | -0.305278 | -2.424853 | 1.876305 | bar | False | ball |
e | 1.009320 | -0.820649 | -0.022101 | bar | True | ball |
f | 0.490864 | -0.196651 | -1.365382 | bar | True | ball |
h | -1.342600 | -0.054322 | 0.196686 | bar | False | ball |
df2 = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])#增加新的行并填充为NaN
df2
one | two | three | four | five | six | |
---|---|---|---|---|---|---|
a | 0.949488 | 0.851231 | -0.654962 | bar | True | ball |
b | NaN | NaN | NaN | NaN | NaN | NaN |
c | 0.785113 | -0.640581 | -0.532271 | bar | True | ball |
d | NaN | NaN | NaN | NaN | NaN | NaN |
e | -0.231192 | 1.740489 | 0.421804 | bar | False | ball |
f | -0.474195 | 0.255573 | 0.057918 | bar | False | ball |
g | NaN | NaN | NaN | NaN | NaN | NaN |
h | 1.340623 | 0.793281 | -0.114751 | bar | True | ball |
df2
one | two | three | four | five | six | |
---|---|---|---|---|---|---|
a | 0.949488 | 0.851231 | -0.654962 | bar | True | ball |
b | 0.000000 | NaN | NaN | NaN | NaN | NaN |
c | 0.785113 | -0.640581 | -0.532271 | bar | True | ball |
d | 0.000000 | NaN | NaN | NaN | NaN | NaN |
e | -0.231192 | 1.740489 | 0.421804 | bar | False | ball |
f | -0.474195 | 0.255573 | 0.057918 | bar | False | ball |
g | 0.000000 | NaN | NaN | NaN | NaN | NaN |
h | 1.340623 | 0.793281 | -0.114751 | bar | True | ball |
读取Excel数据
#读取excel数据
import pandas as pd
FileReadPath = r"D:\AI\Others\test.xlsx"
df = pd.read_excel(FileReadPath)
df.head()
写Excel数据
#把数据写入Excel
import pandas as pd
data = {'country':['aaa','btb','ccc'],
'population':[10,12,14]}
df = pd.DataFrame(data)#构建DataFrame结构
FileWritePath = r"D:\AI\Others\test1.xlsx"
writer = pd.ExcelWriter(FileWritePath)
df.to_excel(writer,'Sheet1')
writer.save()