pandas DataFrame

DataFrame是二维数组,是Series容器。DataFrame既有行索引,也有列索引。
行索引,即横向索引,index,0轴,axis=0
列索引,即纵向索引,columns,1轴,axis=1

DataFrame创建

#方式1,使用numpy的方法创建
t = pd.DataFrame(np.arange(12).reshape(3,4))
print(t)
>>>
   0  1   2   3
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

#指定行索引和列索引
t = pd.DataFrame(np.arange(12).reshape(3,4),index=['a','b','c'],columns=['d','e','f','g'])
print(t)
>>>
   d  e   f   g
a  0  1   2   3
b  4  5   6   7
c  8  9  10  11

#方式2,使用字典创建,键变成列索引
tmp_dict = {"name":["xiaobai","xiaohei"],"age":[10,20],"sex":["male","female"]}
df = pd.DataFrame(tmp_dict)
print(df)
>>>
      name  age     sex
0  xiaobai   10    male
1  xiaohei   20  female

#方式3,使用list创建
tmp_list = [{"name":"xiaobai","age":10,"sex":"male"},{"name":"xiaohei","age":20,"sex":"female"},{"name":"xiaolan","age":"15"}]
df = pd.DataFrame(tmp_list)
print(df)
>>>
      name age     sex
0  xiaobai  10    male
1  xiaohei  20  female
2  xiaolan  15     NaN

DataFrame属性

tmp_list = [{"name":"xiaobai","age":10,"sex":"male"},{"name":"xiaohei","age":20,"sex":"female"},{"name":"xiaolan","age":15}]
df = pd.DataFrame(tmp_list)
print(df)
>>>
      name  age     sex
0  xiaobai   10    male
1  xiaohei   20  female
2  xiaolan   15     NaN

print(df.index) #行索引
>>>RangeIndex(start=0, stop=3, step=1)

print(df.columns)#列索引
>>>Index(['name', 'age', 'sex'], dtype='object')

print(df.values,type(df.values))#值和值类型
>>>
[['xiaobai' 10 'male']
 ['xiaohei' 20 'female']
 ['xiaolan' 15 nan]] <class 'numpy.ndarray'>

print(df.shape)#形状
>>>(3, 3)

print(df.dtypes)#每列的数据类型
>>>
name    object
age      int64
sex     object
dtype: object

print(df.ndim)#维度
>>>2

print(df.head(2))#不指定默认显示前5行
print(df.tail(2))#不指定默认显示后5行

print(df.info())#信息概览:行数量、列数量、列非空值个数、列数据类型,内存占用
>>>
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
name    3 non-null object
age     3 non-null int64
sex     2 non-null object
dtypes: int64(1), object(2)
memory usage: 200.0+ bytes

print(df.describe())#只对数值列统计
>>>
        age
count   3.0
mean   15.0
std     5.0
min    10.0
25%    12.5
50%    15.0
75%    17.5
max    20.0

DataFrame按照某行或某列排序

tmp_list = pd.DataFrame(np.array([1,3,5,0,9,7,2,19,11,33,99,52]).reshape(3,4),columns=["A","B","C","D"],index=['a','b','c'])
df = pd.DataFrame(tmp_list)
print(df)
>>>
    A   B   C   D
a   1   3   5   0
b   9   7   2  19
c  11  33  99  52

#按照C列倒序
df = df.sort_values(by="C",ascending=False)#默认axis=0,即按照列排序
print(df)
>>>
    A   B   C   D
c  11  33  99  52
a   1   3   5   0
b   9   7   2  19

#按照b行正序
df = df.sort_values(by="b",ascending=True,axis=1)
print(df)
>>>
    C   B   A   D
a   5   3   1   0
b   2   7   9  19
c  99  33  11  52

DataFrame取行或列,示例1

tmp_list = [{"name":"xiaobai","age":10,"sex":"male"},{"name":"xiaohei","age":20,"sex":"female"},
{"name":"xiaolan","age":15},{"name":"xiaohui","age":18,"sex":"female"},{"name":"xiaohong","age":19,"sex":"female"}]
df = pd.DataFrame(tmp_list)
print(df)
>>>
       name  age     sex
0   xiaobai   10    male
1   xiaohei   20  female
2   xiaolan   15     NaN
3   xiaohui   18  female
4  xiaohong   19  female

#取name列第3行值
print(df['name'][3])
>>>
xiaohui

#取两行数据
print(df[:2])
>>>
      name  age     sex
0  xiaobai   10    male
1  xiaohei   20  female

#取name这一列数据,得到的是Series类型
print(df["name"],type(df["name"]))
>>>
0     xiaobai
1     xiaohei
2     xiaolan
3     xiaohui
4    xiaohong
Name: name, dtype: object <class 'pandas.core.series.Series'>

#取[0,2)行的name列
print(df[:2]["name"])
>>>
0    xiaobai
1    xiaohei
Name: name, dtype: object

DataFrame取行或列,示例2

t = pd.DataFrame(np.arange(12).reshape(3,4),index=["a","b","c"],columns=["A","B","C","D"])
print(t)
>>>
   A  B   C   D
a  0  1   2   3
b  4  5   6   7
c  8  9  10  11

#取a行B列的值
print(t.loc["a","B"])
print(type(t.loc["a","B"]))
>>>1
>>><class 'numpy.int32'>

#取a行,列取a行的全部列,方式1
print(t.loc["a"])
print(type(t.loc["a"]))
>>>
A    0
B    1
C    2
D    3
Name: a, dtype: int32
>>><class 'pandas.core.series.Series'>

#取a行,列取a行的全部列,方式2
print(t.loc["a",:])
print(type(t.loc["a",:]))
>>>
A    0
B    1
C    2
D    3
Name: a, dtype: int32
>>><class 'pandas.core.series.Series'>

#取B列,行取所有行
print(t.loc[:,"B"])
print(type(t.loc[:,"B"]))
>>>
a    1
b    5
c    9
Name: B, dtype: int32
>>><class 'pandas.core.series.Series'>

#取a行和b行,方式1
print(t.loc[["a","b"]])
>>>
   A  B  C  D
a  0  1  2  3
b  4  5  6  7

#取a行和b行,方式2
print(t.loc[["a","b"],:])
>>>
   A  B  C  D
a  0  1  2  3
b  4  5  6  7

#取A列和B列
print(t.loc[:,["A","B"]])
>>>
   A  B
a  0  1
b  4  5
c  8  9

#取a和c行  A和B列
print(t.loc[["a","c"],["A","B"]])
>>>
   A  B
a  0  1
c  8  9

#使用切片方式取a~c行,A~B列。注意:包含a、c,A、B
print(t.loc["a":"c","A":"B"])
>>>
   A  B
a  0  1
b  4  5
c  8  9

#iloc方法取所有行,第4列和第2列数据
print(t.iloc[:,[3,1]])
>>>
    D  B
a   3  1
b   7  5
c  11  9

#iloc取第1行和第2行,第4列和第2列数据
print(t.iloc[[0,2],[3,1]])
>>>
    D  B
a   3  1
c  11  9

#iloc取第2行之后,包含第2行。第3列之前,不包含第3列
print(t.iloc[1:,:2])
>>>
   A  B
b  4  5
c  8  9

#iloc取第2行之后,包含第2行。第3列之前,不包含第3列。赋值
t.iloc[1:,:2] = 100
print(t)
>>>
     A    B   C   D
a    0    1   2   3
b  100  100   6   7
c  100  100  10  11

DataFrame按条件筛选

tmp_list = [{"name":"xiaobai","age":10,"sex":"male"},{"name":"xiaohei","age":20,"sex":"female"},
{"name":"xiaolan","age":15},{"name":"xiaohui","age":18,"sex":"female"},{"name":"xiaohong","age":19,"sex":"female"}]
df = pd.DataFrame(tmp_list)
print(df)
>>>
       name  age     sex
0   xiaobai   10    male
1   xiaohei   20  female
2   xiaolan   15     NaN
3   xiaohui   18  female
4  xiaohong   19  female

#查找age>15
df1 = df[df["age"] > 15]
print(df1)
>>>
       name  age     sex
1   xiaohei   20  female
3   xiaohui   18  female
4  xiaohong   19  female

#查找age>15并且age<20
df1 = df[(df["age"] > 15)&(df["age"] < 20)]
print(df1)
>>>
       name  age     sex
3   xiaohui   18  female
4  xiaohong   19  female

#查找age>15或age<13
df1 = df[(df["age"] > 15) | (df["age"] < 13)]

#查找name字符长度>7的数据
df1 = df[df["name"].str.len() >7]
print(df1)
>>>
       name  age     sex
4  xiaohong   19  female
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容