Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การเพิ่ม Column ใหม่เข้า DataFrame โดยใช้ Series ใน Pandas Python

วิธีหนึ่งในการเพิ่ม Column ใหม่คือ สร้าง Series ใหม่ (พร้อม Index ที่ตรงกับ DataFrame) แล้ว Assign ให้ DataFrame

ตัวอย่างโค้ด


import pandas as pd

my_data = {
    'ab': pd.Series([1, 8, 7], index=['a', 'b', 'c']),
    'cd': pd.Series([1, 2, 0, 9], index=['a', 'b', 'c', 'd'])
}

my_df = pd.DataFrame(my_data)
print("The dataframe is:")
print(my_df)

# เพิ่ม Column 'ef' โดยสร้าง Series ใหม่
my_df['ef'] = pd.Series([56, 78, 32], index=['a', 'b', 'c'])

print("\nAfter adding a new column 'ef':")
print(my_df)

ผลลัพธ์


The dataframe is:
    ab  cd
a  1.0   1
b  8.0   2
c  7.0   0
d  NaN   9

After adding a new column 'ef':
    ab  cd   ef
a  1.0   1  56.0
b  8.0   2  78.0
c  7.0   0  32.0
d  NaN   9  NaN

คำอธิบาย

  • DataFrame เดิมมี Index a,b,c,d (Union ของ ab และ cd)

  • Series ใหม่ 'ef' มี Index a,b,c เท่านั้น

  • Assign: my_df['ef'] = new_series - Align ตาม Index

  • Index 'd' ไม่มีใน Series ใหม่ → ได้ NaN

วิธีเพิ่ม Column ทั้งหมด (Summary)

วิธีCode Example 특징
Direct Assign (List/Array)df['new'] = [1,2,3,4]ต้องยาวเท่า Index, ไม่ Align
Direct Assign (Scalar)df['new'] = 0Broadcast ทุก Row
Assign Seriesdf['new'] = pd.Series([...], index=...)Align ตาม Index (ปลอดภัย)
Assign from Existingdf['new'] = df['A'] + df['B']Auto-align, Vectorized
df.assign()df = df.assign(new=df['A']+df['B'])Immutable, Method Chaining
df.eval()df.eval('new = A + B', inplace=True)String Expression, เร็ว

การเพิ่มหลาย Column พร้อมกัน


# Dictionary
df[['col1', 'col2']] = pd.DataFrame({'col1': [1,2], 'col2': [3,4]}, index=df.index)

# assign() หลายตัว
df = df.assign(
    col1=lambda x: x['A'] * 2,
    col2=lambda x: x['B'] + 10
)

Best Practice: ใช้ Series พร้อม Index หรือ Vectorized Operations เพื่อความปลอดภัยและประสิทธิภาพ