Как мне создать новый фрейм данных и заменить значения в определенном столбце одним оператором?
Скажи, что у меня есть следующее:
import pandas as pd
import numpy as np
student_ids = ['abc123', 'def321', 'qwe098', 'rty135']
extra_junk = ['whoa', 'hey', 'don\'t touch me', 'junk']
gpas = ['3.1', 'junk', 'NaN', '2.75']
aa = np.array([student_ids, extra_junk, gpas]).transpose()
df = pd.DataFrame(data= aa, columns=['student_id', 'extra_junk', 'gpa'])
>>> df
student_id extra_junk gpa
0 abc123 whoa 3.1
1 def321 hey junk
2 qwe098 don't touch me NaN
3 rty135 junk 2.75
Я могу сделать это в два раза:
df2 = df.copy()
df2['gpa'] = df2['gpa'].replace('junk', 'NaN')
>>> df2
student_id extra_junk gpa
0 abc123 whoa 3.1
1 def321 hey NaN
2 qwe098 don't touch me NaN
3 rty135 junk 2.75