python-3.x - 如何使用具有相同列名的向量设置一些行值?
问题描述
我想要一种快速有效的方法来根据另一个数据帧中的值设置每一行中的“col_1”和“col_2”列中的值,并在 ['b','c'] 中设置一个“id”。下面是我如何尝试使用 df.update 执行此操作的一个简单示例。
data = {'id': ['a', 'b', 'b', 'c'],
'col_0': ['e','f','g','h'],
'col_1': ['m','n','o','p'],
'col_2': ['q','r','s','t']}
df=pd.DataFrame.from_dict(data)
df
#the data frame dictating the changes to be made
cols=['col_1','col_2']
chg_dict={'b': ['b_0','b_1'],'c': ['c_0','c_1']}
chg_df=pd.DataFrame.from_dict(chg_dict,orient='index',columns=cols)
chg_df
#make the change
for chg in chg_df.index:
#mask to get index where id is in chg_dict
mask=[r for r in df.index if df.loc[r,'id']==chg]
#this is apparently where I go wrong, nothing changes
df.loc[mask,cols].update(chg_df)
df
我尝试过使用和不使用 cols 索引器。
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.update.html
解决方案
据我了解,您可以尝试这样做:
m=df.set_index('id')
m.update(chg_df)
df=m.reset_index()
print(df)
id col_0 col_1 col_2
0 a e m q
1 b f b_0 b_1
2 b g b_0 b_1
3 c h c_0 c_1
推荐阅读
- java - 在类构造函数中使用枚举
- ubuntu - 无法在jetson agx xavier上安装anaconda
- html - Safari Web 和移动浏览器上的导航栏包装
- flutter - 显示所有用户数据,想在我的个人资料部分显示仅记录的用户数据
- ios - 从 3d 模型测量 iOS 中的建筑面积
- python - 匹配单个表中的记录,然后比较每条记录中的特定列
- laravel-8 - 触发事件并重新渲染组件后,Livewire 加载 javascript
- angular - 角度模块如何使用另一个模块并用自定义值实例化它?
- swift - 快速更改背景颜色并在 UIVIew 中有圆角?
- javascript - javascript创建具有不同属性的html