1. 字典,转换为dataframe
my_dict = {
3: 'apple',
2: 'banana',
6: 'mango',
4: 'apricot',
1: 'kiwi',
8: 'orange'}
#分别表示
print(my_dict.keys())
print(my_dict.values())
print(my_dict.items())
# dict_keys([3,2,6,4,1,8])
# dict_values(['apple','banana','mango','apricot','kiwi','orange'])
# dict_items([(3,'apple'),(2,'banana'),(6,'mango'),(4,'apricot'),(1,'kiwi'),(8,'orange')])
#依据keys筛选字典所需内容
new_dict = {k:v for k,v in my_dict.items() if k in [1,2,3,4]}
print(new_dict)
# 3: 'apple',
2: 'banana',
4: 'apricot',
1: 'kiwi'
#将字段转化为dataframe
df = pd.DataFrame(list(fruit_dict.items()),
columns=['Quantity', 'FruitName']))
2. 实现excel中vlookup
# 创建表1
df1 = pd.DataFrame({
'A': ['apple', 'banana', 'cherry', 'kiwi'],
'B': [30, 20, 25, 15]
})
# 创建表2
df2 = pd.DataFrame({
'A': ['banana', 'cherry', 'kiwi', 'pear'],
'C': ['good', 'better', 'best', 'bad'],
'D': ['1', 'better', 'best', 'bad']
})
# 使用VLOOKUP将表2中的'C'列和'D'列数据匹配到表1中
df3 = df1.merge(df2[['A', 'C','D']], on='A', how='left')
# 将匹配结果输出
print(df3)
3. Pandas 数据中的loc与iloc含义以及操作
df.loc[]只能使用标签索引,不能使用整数索引,通过便签索引切边进行筛选时,前闭后闭。
df.iloc[]只能使用整数索引,不能使用标签索引,通过整数索引切边进行筛选时,前闭后开。
#dafaframe如下
name age gender isMarried
a Joe 25.0 1 yes
b Mike 32.0 0 yes
c Jack 18.0 1 no
d Rose NaN 1 yes
e David 15.0 0 no
f Marry 20.0 1 no
g Wansi 41.0 0 no
h Sidy NaN 0 yes
i Jason 37.0 1 no
j Even 32.0 0 no
#输出
name age gender isMarried
b Mike 32.0 0 yes
g Wansi 41.0 0 no
i Jason 37.0 1 no
j Even 32.0 0 no
方法1:
df.loc[df.loc[:,'age']>30, :]
方法2:
df.loc[df.iloc[:,1]>30, :]