自用:备份

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, :]



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值