วิธีวนซ้ำคอลัมน์ใน pandas dataframe
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อวนซ้ำคอลัมน์ของ DataFrame ของแพนด้า:
for name, values in df. iteritems ():
print (values)
ตัวอย่างต่อไปนี้แสดงวิธีการใช้ไวยากรณ์นี้ในทางปฏิบัติกับ Pandas DataFrame ต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19], ' assists ': [5, 7, 7, 9, 12], ' rebounds ': [11, 8, 10, 6, 6]}) #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6
ตัวอย่างที่ 1: วนซ้ำคอลัมน์ทั้งหมดของ DataFrame
รหัสต่อไปนี้แสดงวิธีการวนซ้ำแต่ละคอลัมน์ของ Pandas DataFrame:
for name, values in df. iteritems ():
print (values)
0 25
1 12
2 15
3 14
4 19
Name: points, dtype: int64
0 5
1 7
2 7
3 9
4 12
Name: assists, dtype: int64
0 11
1 8
2 10
3 6
4 6
Name: rebounds, dtype: int64
นอกจากนี้เรายังสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อวนซ้ำแต่ละคอลัมน์และพิมพ์เฉพาะชื่อคอลัมน์:
for name, values in df. iteritems ():
print (name)
points
assists
rebounds
ตัวอย่างที่ 2: วนซ้ำคอลัมน์ที่ระบุ
ไวยากรณ์ต่อไปนี้แสดงวิธีการวนซ้ำคอลัมน์เฉพาะใน DataFrame ของแพนด้า:
for name, values in df[[' points ', ' rebounds ']]. iteritems ():
print (values)
0 25
1 12
2 15
3 14
4 19
Name: points, dtype: int64
0 11
1 8
2 10
3 6
4 6
Name: rebounds, dtype: int64
นอกจากนี้เรายังสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อวนซ้ำในช่วงของคอลัมน์เฉพาะ:
for name, values in df. iloc [:, 0:2] . iteritems ():
print (values)
0 25
1 12
2 15
3 14
4 19
Name: points, dtype: int64
0 5
1 7
2 7
3 9
4 12
Name: assists, dtype: int64
คุณสามารถดูเอกสารฉบับเต็มสำหรับฟังก์ชัน iteritems() ได้ที่นี่
แหล่งข้อมูลเพิ่มเติม
วิธีใช้ฟังก์ชันกับคอลัมน์ที่เลือกใน Pandas
วิธีเปลี่ยนลำดับคอลัมน์ใน Pandas
วิธีลบคอลัมน์ตามดัชนีใน Pandas