使用Pandas中很好的索引方法,我可以通过各种方式提取数据。另一方面,我仍然对如何更改现有DataFrame中的数据感到困惑。
在下面的代码中,我有两个DataFrames,我的目标是从第二个df的值更新第一个df中特定行中的值。我如何才能做到这一点?
import pandas as pd
df = pd.DataFrame({'filename' : ['test0.dat', 'test2.dat'],
'm': [12, 13], 'n' : [None, None]})
df2 = pd.DataFrame({'filename' : 'test2.dat', 'n':16}, index=[0])
# this overwrites the first row but we want to update the second
# df.update(df2)
# this does not update anything
df.loc[df.filename == 'test2.dat'].update(df2)
print(df)
给出
filename m n
0 test0.dat 12 None
1 test2.dat 13 None
[2 rows x 3 columns]
但是,我如何才能做到这一点:
filename m n
0 test0.dat 12 None
1 test2.dat 13 16
[2 rows x 3 columns]
发布于 2021-01-09 18:09:30
在SQL中,我可以一次完成它,如下所示
update table1 set col1 = new_value where col1 = old_value
但是在Python Pandas中,我们可以这样做:
data = [['ram', 10], ['sam', 15], ['tam', 15]]
kids = pd.DataFrame(data, columns = ['Name', 'Age'])
kids
这将生成以下输出:
Name Age
0 ram 10
1 sam 15
2 tam 15
现在我们可以运行:
kids.loc[kids.Age == 15,'Age'] = 17
kids
它将显示以下输出
Name Age
0 ram 10
1 sam 17
2 tam 17
它应该等同于下面的SQL
update kids set age = 17 where age = 15
发布于 2014-06-04 22:05:42
如果你有一个很大的数据帧,并且只有几个更新值,我会像这样使用apply:
import pandas as pd
df = pd.DataFrame({'filename' : ['test0.dat', 'test2.dat'],
'm': [12, 13], 'n' : [None, None]})
data = {'filename' : 'test2.dat', 'n':16}
def update_vals(row, data=data):
if row.filename == data['filename']:
row.n = data['n']
return row
df.apply(update_vals, axis=1)
发布于 2014-06-04 20:15:33
可能有几种方法可以做到这一点,但一种方法是在filename/m列上将两个数据帧合并在一起,如果找到匹配的数据帧,则从正确的数据帧填充列'n‘。代码中的n_x、n_y引用合并中的左/右数据帧。
In[100] : df = pd.merge(df1, df2, how='left', on=['filename','m'])
In[101] : df
Out[101]:
filename m n_x n_y
0 test0.dat 12 None NaN
1 test2.dat 13 None 16
In[102] : df['n'] = df['n_y'].fillna(df['n_x'])
In[103] : df = df.drop(['n_x','n_y'], axis=1)
In[104] : df
Out[104]:
filename m n
0 test0.dat 12 None
1 test2.dat 13 16
https://stackoverflow.com/questions/24036911
复制相似问题