Python3 - Pandas DataFrames: loc, iloc,drop, insert

DataFrames: Two-dimensional size-mutable, potentially heterogeneous tabular data.

import pandas as pd
import numpy as np

np.random.seed(101)
df = pd.DataFrame(np.random.randn(5,4),['A','B','C','D','E'],['W','X','Y','Z'])
print(df)

print("***** 选择特定的cell (B,Y) ******")
print(df.loc['B', 'Y'])

print("**** 选择特定的列 ****")
print(df['W'])
# print(df.W)  #最好别用这种方式,很混淆
print(type(df['W']))

print("***** 选择特定的列 *****")
print(df[['W','Z']])
print(df[['X','Z']])

print("***** 选择特定的行 ******")
print(df.loc['A'])
print(df.iloc[0])

print(df.loc[['A','C']])
print('\n')
print(df.iloc[[0,2]])

print("****** 选择特定的行和列 ******")
print(df.loc[['A','C'],['W','Y']])

print("****** 创建新的列 ******")
df['new'] = df['W'] + df['Y']
print(df)

new_data = np.random.randn(5,1)
df.insert(5,"new_data", new_data)
print(df)

print("****** 删除列 *******")
print(df.drop('new',axis=1))  #因为shape是个tuple, 根据index来表示行列

print("******* 删除行 *********")
print(df.drop('A',axis=0))

结果如下:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
如果觉得不错,就点赞或关注或留言~~
谢谢 ~ ~

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值