日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

詳解pandas中Series()和DataFrame()的區(qū)別與聯(lián)系_python

作者:我是小螞蟻 ? 更新時(shí)間: 2023-02-26 編程語言

區(qū)別:

  • series,只是一個(gè)一維數(shù)據(jù)結(jié)構(gòu),它由index和value組成。
  • dataframe,是一個(gè)二維結(jié)構(gòu),除了擁有index和value之外,還擁有column。

聯(lián)系:

  • dataframe由多個(gè)series組成,無論是行還是列,單獨(dú)拆分出來都是一個(gè)series。

代碼演示:

import numpy as np
import pandas as pd
from pandas import Series, DataFrame

data = {'Country':['Belgium', 'India', 'Brazil'],
? ? ? ? 'Capital':['Brussels', 'New Delhi', 'Brasilia'],
? ? ? ? 'Population':[11190846, 1303171035, 207847528]
? ? ? ? }

# Series

s1 = Series(data['Country'])
print(s1)
'''
0 ? ?Belgium
1 ? ? ?India
2 ? ? Brazil
dtype: object
'''
print(s1.values) # 類型: <class 'numpy.ndarray'>
'''
['Belgium' 'India' 'Brazil']
'''
print(s1.index)
'''
RangeIndex(start=0, stop=3, step=1)
'''

# 為Series指定index
s1 = Series(data['Country'], index=['A', 'B', 'C'])
print(s1)
''' 索引更改
A ? ?Belgium
B ? ? ?India
C ? ? Brazil
dtype: object
'''


# Dataframe

df1 = pd.DataFrame(data)
print(df1)
'''
? ? ?Capital ?Country ?Population
0 ? Brussels ?Belgium ? ?11190846
1 ?New Delhi ? ?India ?1303171035
2 ? Brasilia ? Brazil ? 207847528
'''

print(df1['Capital']) # 類型: series
'''
0 ? ? Brussels
1 ? ?New Delhi
2 ? ? Brasilia
Name: Capital, dtype: object
'''


print(df1.iterrows()) # 返回 一個(gè) 生成器 <generator object DataFrame.iterrows at 0x7f226a67b728>

for row in df1.iterrows():
? ? print(row)
? ? print(row[0], row[1])
? ? print(type(row[0]), type(row[1]))
? ? break
'''?
print(row) 返回了一個(gè)元組
(0, Capital ? ? ? Brussels
Country ? ? ? ?Belgium
Population ? ?11190846
Name: 0, dtype: object)
'''
'''
print(row[0], row[1]) 的返回值
0 Capital ? ? ? Brussels
Country ? ? ? ?Belgium
Population ? ?11190846
Name: 0, dtype: object
'''
'''
print(type(row[0]), type(row[1]))
<class 'int'> <class 'pandas.core.series.Series'>

row[1] 是一個(gè) series,而且原來的列名,現(xiàn)在變成了現(xiàn)在的索引名,
由此可見,dataframe是由多個(gè)行列交錯(cuò)的series組成。
'''

# 現(xiàn)在可以 構(gòu)建幾個(gè)series
s1 = pd.Series(data['Country'])
s2 = pd.Series(data['Capital'])
s3 = pd.Series(data['Population'])
df_new = pd.DataFrame([s1, s2, s3], index=['Country', 'Captital', 'Population'])
print(df_new)
'''
? ? ? ? ? ? ? ? ? ?0 ? ? ? ? ? 1 ? ? ? ? ?2
Country ? ? ?Belgium ? ? ? India ? ? Brazil
Captital ? ?Brussels ? New Delhi ? Brasilia
Population ?11190846 ?1303171035 ?207847528

可以看到,行 和 列 都是顛倒的,因此需要進(jìn)行一下轉(zhuǎn)置
'''

print(df_new.T)
'''
? ?Country ? Captital ?Population
0 ?Belgium ? Brussels ? ?11190846
1 ? ?India ?New Delhi ?1303171035
2 ? Brazil ? Brasilia ? 207847528

'''

'''
總結(jié):
? ? series, 就是一個(gè) 一維 的數(shù)據(jù)結(jié)構(gòu),它是由 index 和?。觯幔欤酰濉〗M成。
? ? dataframe, 是一個(gè) 二維 數(shù)據(jù)結(jié)構(gòu),它由多個(gè) series 構(gòu)成。
'''

原文鏈接:https://blog.csdn.net/missyougoon/article/details/83301712

欄目分類
最近更新