认识pandas的Dataframe和 Series,以及它们之间的运算

本文介绍了pandas的Dataframe和Series数据结构。Dataframe包含column和index,类似于表格形式。通过实例展示了如何创建DataFrame,打印、转换、获取列以及进行运算,如转置、减法操作。当进行DataFrame与Series运算时,需注意索引对齐的重要性。
摘要由CSDN通过智能技术生成

Dataframe 有column 和 index ,column也是key。像平常的表格。见下列例子:
df = pd.DataFrame(np.arange(1,16).reshape(3,5),columns=[‘A’,‘B’,‘C’,‘D’,‘E’],index=[‘one’,‘two’,‘three’])

‘’’
print(df)
输出:
A B C D E
one 1 2 3 4 5
two 6 7 8 9 10
three 11 12 13 14 15

‘’’
‘’’
print(df.keys())
输出: Index([‘A’, ‘B’, ‘C’, ‘D’, ‘E’], dtype=‘object’)

print(df[‘D’].keys())
output: Index([‘one’, ‘two’, ‘three’], dtype=‘object’)

print(df[“D”])
输出:
one 4
two 9
three 14
Name: D, dtype: int32
‘’’
dft = df.transpose()
‘’’
print(dft)
one two three
A 1 6 11
B 2 7 12
C 3 8 13
D 4 9 14
E 5 10 15
‘’’
‘’’
print(dft.keys())
输出: Index([‘one’, ‘two’, ‘three’], dtype=‘object’)
‘’’
‘’’
print(dft[‘one’].keys())
output: Index([‘A’, ‘B’, ‘C’, ‘D’, ‘E’], dtype=‘object’)
‘’’
‘’’
print(dft[‘one’])
output:
A 1
B 2
C 3
D 4
E 5
Name: one, dtype: int32
‘’’
‘’’
X = df - dft[‘one’]
print(X)
A B C D E
one 0 0 0 0 0
two 5 5 5 5 5
three 10 10 10 10 10
‘’’

s = pd.Series([1,2,3,4,5])
Y = df - s
‘’’
print(Y)
output:
A B C D E 0 1 2 3 4
one NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
two NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
three NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
‘’’

s.index=[‘A’,‘B’,‘C’,‘D’,‘E’]
Y = df - s
‘’’
print(Y)
output:
A B C D E
one 0 0 0 0 0
two 5 5 5 5 5
three 10 10 10 10 10
‘’’

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值