Pandas学习笔记(2):Pandas的使用补充


引言

在数据科学和分析领域,Pandas库因其强大的数据处理能力而广受欢迎。本文将通过一系列示例,详细介绍Pandas库中的一些常用功能,包括遍历Series和DataFrame、排序、去重、分组、合并、时间戳处理、抽样、处理空值以及数据可视化等操作。

遍历Series和DataFrame

在Pandas中,我们可以通过多种方式遍历Series和DataFrame。以下是一些常用的方法:

直接遍历Series

s = pd.Series([1, 2, 3, 4, 5, 6])
for i in s:
    print(i)

输出结果:

1
2
3
4
5
6

通过items()方法获得index和value遍历

for i, v in s.items():
    print(f'index: {i}, value: {v}')

输出结果:

index: 0, value: 1
index: 1, value: 2
index: 2, value: 3
index: 3, value: 4
index: 4, value: 5
index: 5, value: 6

通过index进行遍历

for i in s.index:
    print(f'index: {i}, value: {s[i]}')

输出结果:

index: 0, value: 1
index: 1, value: 2
index: 2, value: 3
index: 3, value: 4
index: 4, value: 5
index: 5, value: 6

通过values进行遍历

for i in s.values:
    print(f'value: {i}')

输出结果:

value: 1
value: 2
value: 3
value: 4
value: 5
value: 6

直接遍历DataFrame

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
for i in df:
    print(i)

输出结果:

A
B

使用iterrows()遍历DataFrame

for index, row in df.iterrows():
    print(f'index: {index}, row: {row}')
    for v in row:
        print(v)

输出结果:

index: 0, row: A    1
B    4
Name: 0, dtype: int64
1
4
index: 1, row: A    2
B    5
Name: 1, dtype: int64
2
5
index: 2, row: A    3
B    6
Name: 2, dtype: int64
3
6

使用itertuples()遍历DataFrame

for row in df.itertuples(index=False):
    print(row)
    for v in row:
        print(v)

输出结果:

(1, 4)
1
4
(2, 5)
2
5
(3, 6)
3
6

按列遍历DataFrame

for name, item in df.items():
    print(f'name: {name}, item: {item}')

输出结果:

name: A, item: Int64Index([0, 1, 2], dtype='int64')
0    1
1    2
2    3
Name: A, dtype: int64
name: B, item: Int64Index([0, 1, 2], dtype='int64')
0    4
1    5
2    6
Name: B, dtype: int64

使用loc方法遍历DataFrame

for index in df.index:
    for col in df.columns:
        print(f'index:{index}, value:{df.loc[index, col]}')

输出结果:

index:0, value:1
index:0, value:4
index:1, value:2
index:1, value:5
index:2, value:3
index:2, value:6

loc方法通过布尔索引获取行数据

print(df.loc[df['A'] > 2])

输出结果:

   A  B
2  3  6

排序

Pandas提供了sort_index()sort_values()方法来对DataFrame进行排序。

按行标签排序

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['c', 'b', 'a'])
df1 = df.sort_index(ascending=False)
print(df1)

输出结果:

   A  B
c  3  6
b  2  5
a  1  4

按列排序

df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
    'Age': [25, 30, 25, 35, 30],
    'Score': [85, 90, 80, 95, 88]
})
print(df.sort_values(['Age', 'Score'], ascending=[True, False]))

输出结果:

      Name  Age  Score
2  Charlie   25     80
0    Alice   25     85
4      Eve   30     88
1      Bob   30     90
3    David   35     95

去重

使用drop_duplicates()方法可以去除DataFrame中的重复行。

data = {
    'A': [1, 2, 2, 3],
    'B': [4, 5, 5, 6],
    'C': [7, 8, 8, 9]
}
df = pd.DataFrame(data)
df1 = df.drop_duplicates(keep='last')
print(df1)

输出结果:

   A  B  C
0  1  4  7
1  2  5  8
3  3  6  9

分组

groupby()方法可以将DataFrame按照某个列的值进行分组,并对每组数据进行聚合计算。

data = {
    'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
    'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
    'C': [1, 2, 3, 4, 5, 6, 7, 8],
    'D': [10, 20, 30, 40, 50, 60, 70, 80]
}
df = pd.DataFrame(data)

groupbyed = df.groupby('A')
print(list(groupbyed))

输出结果:

[('bar',    A      bar
 B      one
 C      2
 D     20
 Name: 1, dtype: object),
 ('foo',    A      foo
 B      one
 C      1
 D     10
 Name: 0, dtype: object),
 ('foo',    A      foo
 B      two
 C      3
 D     30
 Name: 2, dtype: object),
 ('foo',    A      foo
 B      one
 C      7
 D     70
 Name: 6, dtype: object),
 ('foo',    A      foo
 B    three
 C      8
 D     80
 Name: 7, dtype: object)]
mean1 = groupbyed['C'].mean()
print(mean1)

输出结果:

A
bar    4.666667
foo    4.250000
Name: C, dtype: float64
c_mean = groupbyed['C'].transform(lambda x: x.mean())
df['c_mean'] = c_mean
print(df)

输出结果:

     A      B  C   D     c_mean
0  foo    one  1  10  4.250000
1  bar    one  2  20  4.666667
2  foo    two  3  30  4.250000
3  bar  three  4  40  4.666667
4  foo    two  5  50  4.250000
5  bar    two  6  60  4.666667
6  foo    one  7  70  4.250000
7  foo  three  8  80  4.250000
df1 = df.groupby('A').filter(lambda x: x['D'].mean() > 40)
print(df1)

输出结果:

     A      B  C   D     c_mean
1  bar    one  2  20  4.666667
2  foo    two  3  30  4.250000
3  bar  three  4  40  4.666667
4  foo    two  5  50  4.250000
5  bar    two  6  60  4.666667
7  foo  three  8  80  4.250000

合并

merge()方法允许我们按照某个键(或多个键)将两个DataFrame合并在一起,类似于SQL中的JOIN操作。

left = pd.DataFrame({
    'key': ['K0', 'K1', 'K2', 'K3'],
    'A': ['A0', 'A1', 'A2', 'A3'],
    'B': ['B0', 'B1', 'B2', 'B3']
})

right = pd.DataFrame({
    'key': ['K0', 'K1', 'K2', 'K4'],
    'C': ['C0', 'C1', 'C2', 'C3'],
    'D': ['D0', 'D1', 'D2', 'D3']
})

result = pd.merge(left, right, on='key')
print(result)

输出结果:

   key   A   B   C   D
0  K0  A0  B0  C0  D0
1  K1  A1  B1  C1  D1
2  K2  A2  B2  C2  D2
result1 = pd.merge(left, right, on='key', how='right')
print(result1)

输出结果:

   key   A   B   C   D
0  K0  A0  B0  C0  D0
1  K1  A1  B1  C1  D1
2  K2  A2  B2  C2  D2
3  K4  NaN NaN  C3  D3

时间戳处理

Pandas提供了多种处理时间戳的方法。

t = pd.Timestamp('2024-12-30 13:47:54')
print(t)

输出结果:

2024-12-30 13:47:54
t1 = pd.Timestamp(1735537426159, unit='ms', tz='Asia/Hong_Kong')
print(t1)

输出结果:

Timestamp('2024-12-30 13:47:06+0800', tz='Asia/Hong_Kong')
s = '2024-12-30 13:47:00'
t2 = pd.to_datetime(s)
print(t2)

输出结果:

2024-12-30 13:47:00
t3 = pd.date_range('2024-12-01', '2024-12-10', freq='D')
print(t3)

输出结果:

DatetimeIndex(['2024-12-01', '2024-12-02', '2024-12-03', '2024-12-04',
               '2024-12-05', '2024-12-06', '2024-12-07', '2024-12-08',
               '2024-12-09', '2024-12-10'],
              dtype='datetime64[ns]', freq='D')
td = pd.Timedelta(1, unit='D')
print(td)

输出结果:

1 days
t = pd.Timestamp('2024-12-30')
s = t.strftime('%Y/%m/%d %H:%M:%S')
print(s)

输出结果:

2024/12/30 00:00:00

抽样

sample()方法允许我们从DataFrame中随机抽取样本。

df = pd.DataFrame({
    "company": ['百度', '阿里', '腾讯'],
    "salary": [43000, 24000, 40000],
    "age": [25, 35, 49]
})
df1 = df.sample(2, axis=0)
print(df1)

输出结果(可能因随机性而异):

      company  salary  age
1       阿里   24000   35
2      腾讯   40000   49
df2 = df.sample(1, axis=1)
print(df2)

输出结果(可能因随机性而异):

   salary
0   43000
1   24000
2   40000
df3 = df.sample(frac=0.2, axis=0)
print(df3)

输出结果(可能因随机性而异):

      company  salary  age
2      腾讯   40000   49

处理空值

Pandas提供了fillna()dropna()方法来处理空值。

df = pd.DataFrame({'A': [None, None, None],
                   'B': [4, 5, 6]})
df1 = df.fillna(0)
print(df1)

输出结果:

     A  B
0  0.0  4
1  0.0  5
2  0.0  6
df2 = df.dropna(axis=0, how='any')
print(df2)

输出结果:

Empty DataFrame
Columns: [A, B]
Index: []

数据导出与导入

Pandas提供了to_csv()read_csv()方法,方便我们进行数据的导出和导入。

df = pd.DataFrame([{'name': "zhangsan", 'age': 20},
                   {'name': "lisi", 'age': 21}])
# to_csv:存文件,index=False:在存文件时忽略索引
df.to_csv('demo07.csv', index=False)

df1 = pd.read_csv('demo07.csv')
print(df1)

输出结果:

     name  age
0  zhangsan   20
1      lisi   21

数据可视化

Pandas内置了基于matplotlib的绘图功能,使得数据可视化变得简单。

data = {
    'A': [1, 2, 3, 4, 5],
    'B': [10, 20, 25, 30, 40]
}
df = pd.DataFrame(data)
# df.plot(kind='line')
# df.plot(kind='bar')
# df.plot(kind='hist')
df.plot(kind='scatter', x='A', y='B')
plt.show()

以上代码会生成一个散点图,展示了A和B两列之间的关系。

data = {'A': 10, 'B': 20, 'C': 30, 'D': 40}
df = pd.Series(data)
df.plot(kind='pie', autopct='%1.1f%%')
plt.show()

以上代码会生成一个饼图,展示了各个部分的比例。

这些数据可视化方法可以帮助我们更直观地理解数据的分布和关系。

结论

本文详细介绍了Pandas库中的数据操作功能,包括遍历Series和DataFrame、排序、去重、分组、合并、时间戳处理、抽样、处理空值以及数据可视化等。这些功能在日常的数据处理和分析工作中非常有用,能够帮助我们更高效地管理和分析数据。希望这篇文章能够帮助你更好地理解和使用Pandas库。

附录

  • 额外资源Pandas官方文档提供了更详细的API参考和使用指南。
  • 感谢:感谢Pandas社区的贡献者,他们的努力使得Pandas成为了Python数据分析中不可或缺的工具。

通过这篇文章,你应该能够掌握Pandas库的一些核心功能,并能够将这些知识应用到实际的数据项目中。如果你有任何问题或需要进一步的帮助,请随时在评论区提出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值