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

學無先后,達者為師

網站首頁 編程語言 正文

pandas將Series轉成DataFrame的實現_python

作者:bitcarmanlee ? 更新時間: 2023-03-15 編程語言

1.Series結構

pandas中,我們使用最多的兩個數據結構,分別為Series與DataFrame。

Series跟一維數組比較像,可以認為是dataframe中的"一列"。與一維數組不同的是,除了數組數據以外,他還有一組與數組數據對應的標簽索引。

2.將Series轉成DataFrame

2.1 使用字典的方式轉化

import pandas as pd

department = ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C']
group = ['g1', 'g1', 'g2', 'g3', 'g3', 'g4', 'g5', 'g5']
data = pd.DataFrame({'department': department, 'group': group})

d2 = data.groupby('department')['group'].apply(lambda x: ",".join(x))
print("d2 is: ", '\n', d2, "\nd2 type is: ", type(d2), '\n')
d2 = pd.DataFrame({'department': d2.index, 'group': d2.values})
print("after change, d2 is: ", '\n', d2, '\nd2 type is: ', type(d2), '\n')

上面的代碼中,data進行groupby操作以后取group列,得到的就是一個Series結構。

d2 is:  
 department
A    g1,g1,g2
B    g3,g3,g4
C       g5,g5
Name: group, dtype: object 
d2 type is:  <class 'pandas.core.series.Series'> 

該Series的index是department列,department列的值為A,B,C。具體的值為group,上面的邏輯是將相同department的group值進行聚合。

我們想將其轉成一個dataframe,可以使用字典的方式,直接創建一個新的dataframe。d2.index表示Series的索引,d2.values表示Series的數據。

after change, d2 is:  
   department     group
0          A  g1,g1,g2
1          B  g3,g3,g4
2          C     g5,g5 
d2 type is:  <class 'pandas.core.frame.DataFrame'> 

2.2 使用reset_index方法

還可以使用reset_index的方式,來將Series轉化為dataframe。

d3 = data.groupby('department')['group'].apply(lambda x: ','.join(x))
d3 = d3.reset_index(name='group')
d3['group'] = d3['group'].map(lambda x: ','.join(sorted(list(set(x.split(','))))))
print(d3)

上面的代碼也將Series轉換成了一個dataframe,與前面稍微有所區別的在于,對group還進行了去重排序操作。

最后輸出的結果為

? department ?group
0 ? ? ? ? ?A ?g1,g2
1 ? ? ? ? ?B ?g3,g4
2 ? ? ? ? ?C ? ? g5

3.apply,applymap, map

import pandas as pd

a = [1, 2, 3, 4, 5]
b = [10, 20, 30, 40, 50]
c = [0.1, 0.2, 0.3, 0.4, 0.5]

data = pd.DataFrame({'a': a, 'b': b, 'c': c})
print(data.apply(max), '\n')
print(data.a.apply(lambda x: x * 2), '\n')

print(data.applymap(lambda x: x+0.01), '\n')

print(data.a.map(lambda x: x+0.02))
a ? ? 5.0
b ? ?50.0
c ? ? 0.5
dtype: float64?

0 ? ? 2
1 ? ? 4
2 ? ? 6
3 ? ? 8
4 ? ?10
Name: a, dtype: int64?

? ? ? a ? ? ?b ? ? c
0 ?1.01 ?10.01 ?0.11
1 ?2.01 ?20.01 ?0.21
2 ?3.01 ?30.01 ?0.31
3 ?4.01 ?40.01 ?0.41
4 ?5.01 ?50.01 ?0.51?

0 ? ?1.02
1 ? ?2.02
2 ? ?3.02
3 ? ?4.02
4 ? ?5.02
Name: a, dtype: float64

apply可以用于Series,也可以用于DataFrame,可以對一列或多列進行操作。
applymap只能作用于dataframe,是對dataframe的每一個元素進行操作。
map只能作用于Series,其對Series中每個元素起作用。

原文鏈接:https://blog.csdn.net/bitcarmanlee/article/details/128661841

欄目分類
最近更新