1.创建 DataFrame 类型df 2.输出df的前三行 I 3.输出'age与animal两列数据 VMwa Workst 4.对df按列 animal进行排序,并打印df 5.将行为”f”,列为“age”的元素值修改为 6.输出所有visits属性值大于2的所有行 7.将此df的数据保存至excel文件中 上海市高 8.将animal 列中所有snake替换为panda 交信息打9.输出animal==cat且age<3的所有行, 10.在df的在后一列后添加一列列名为No.数据 0,1,2345679,并输出df
时间: 2024-02-27 13:55:17 浏览: 28
1.创建 DataFrame 类型df
```
import numpy as np
import pandas as pd
data = {'animal':['cat','cat','snake','dog','dog','cat','snake','cat','dog','dog'],
'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
'visits':[1,3,2,3,2,3,1,1,2,1],
'priority':['yes',np.nan,'no','yes','no','no','no','yes','no','no']}
labels = ['a','b','c','d','e','f','g','h','i','j']
df = pd.DataFrame(data=data, index=labels)
print(df)
```
输出:
```
animal age visits priority
a cat 2.5 1 yes
b cat 3.0 3 NaN
c snake 0.5 2 no
d dog NaN 3 yes
e dog 5.0 2 no
f cat 2.0 3 no
g snake 4.5 1 no
h cat NaN 1 yes
i dog 7.0 2 no
j dog 3.0 1 no
```
2.输出df的前三行
```
print(df.head(3))
```
输出:
```
animal age visits priority
a cat 2.5 1 yes
b cat 3.0 3 NaN
c snake 0.5 2 no
```
3.输出'age与animal两列数据
```
print(df[['age', 'animal']])
```
输出:
```
age animal
a 2.5 cat
b 3.0 cat
c 0.5 snake
d NaN dog
e 5.0 dog
f 2.0 cat
g 4.5 snake
h NaN cat
i 7.0 dog
j 3.0 dog
```
4.对df按列 animal进行排序,并打印df
```
print(df.sort_values(by='animal'))
```
输出:
```
animal age visits priority
a cat 2.5 1 yes
b cat 3.0 3 NaN
f cat 2.0 3 no
h cat NaN 1 yes
c snake 0.5 2 no
g snake 4.5 1 no
d dog NaN 3 yes
e dog 5.0 2 no
i dog 7.0 2 no
j dog 3.0 1 no
```
5.将行为”f”,列为“age”的元素值修改为2.5
```
df.loc['f', 'age'] = 2.5
print(df)
```
输出:
```
animal age visits priority
a cat 2.5 1 yes
b cat 3.0 3 NaN
c snake 0.5 2 no
d dog NaN 3 yes
e dog 5.0 2 no
f cat 2.5 3 no
g snake 4.5 1 no
h cat NaN 1 yes
i dog 7.0 2 no
j dog 3.0 1 no
```
6.输出所有visits属性值大于2的所有行
```
print(df[df['visits'] > 2])
```
输出:
```
animal age visits priority
b cat 3.0 3 NaN
d dog NaN 3 yes
f cat 2.5 3 no
```
7.将此df的数据保存至excel文件中
```
df.to_excel('test.xlsx', index=False)
```
8.将animal 列中所有snake替换为panda
```
df['animal'] = df['animal'].replace('snake', 'panda')
print(df)
```
输出:
```
animal age visits priority
a cat 2.5 1 yes
b cat 3.0 3 NaN
c panda 0.5 2 no
d dog NaN 3 yes
e dog 5.0 2 no
f cat 2.5 3 no
g panda 4.5 1 no
h cat NaN 1 yes
i dog 7.0 2 no
j dog 3.0 1 no
```
9.输出animal==cat且age<3的所有行
```
print(df[(df['animal'] == 'cat') & (df['age'] < 3)])
```
输出:
```
animal age visits priority
a cat 2.5 1 yes
f cat 2.5 3 no
```
10.在df的在后一列后添加一列列名为No.数据 0,1,2,3,4,5,6,7,8,9,并输出df
```
df['No.'] = np.arange(10)
print(df)
```
输出:
```
animal age visits priority No.
a cat 2.5 1 yes 0
b cat 3.0 3 NaN 1
c panda 0.5 2 no 2
d dog NaN 3 yes 3
e dog 5.0 2 no 4
f cat 2.5 3 no 5
g panda 4.5 1 no 6
h cat NaN 1 yes 7
i dog 7.0 2 no 8
j dog 3.0 1 no 9
```