英文:
Pandas: Update multiple rows using list
问题
import pandas as pd
# Your original dataframe
data = {'A': [1, 2, 3, 4, 5],
'B': ['a', 'b', 'c', 'd', 'e'],
'C': ['F', 'F', 'F', 'F', 'F']}
df = pd.DataFrame(data)
# Lists of elements to update and their corresponding replacement values
names = ['a', 'd', 'e']
values = ['T', 'T', 'G']
# Update the dataframe
df.loc[df['B'].isin(names), 'C'] = values
这段代码将根据您提供的两个列表,更新了DataFrame中的值,满足条件的行的'C'列将被相应的值替换。
英文:
I am trying to update pandas dataframe using list.
Dataframe with columns A, B, C
A B C
------
1 a F
2 b F
3 c F
4 d F
5 e F
I have 2 lists, one contains list of elements whose value needs to update from column B
and second contains actual value to replace in column C
.
Elements to update from column B
names=['a', 'd', 'e']
Values to replace in column C
values=['T', 'T', 'G']
Output after update
A B C
------
1 a T
2 b F
3 c F
4 d T
5 e G
How to update the dataframe?
答案1
得分: 3
names = ['a', 'd', 'e']
values = ['T', 'T', 'G']
m = df['B'].isin(names)
df.loc[m, 'C'] = df.loc[m, 'B'].map(dict(zip(names, values)))
效率较低的替代方法:
df['C'] = df['B'].map(dict(zip(names, values))).fillna(df['C'])
df['C'] = df['C'].mask(df['B'].isin(names), df['B'].map(dict(zip(names, values))))
输出结果:
A B C
0 1 a T
1 2 b F
2 3 c F
3 4 d T
4 5 e G
英文:
You can use boolean indexing combined with map
:
names = ['a', 'd', 'e']
values = ['T', 'T', 'G']
m = df['B'].isin(names)
df.loc[m, 'C'] = df.loc[m, 'B'].map(dict(zip(names, values)))
Less efficient alternatives:
df['C'] = df['B'].map(dict(zip(names, values))).fillna(df['C'])
df['C'] = df['C'].mask(df['B'].isin(names), df['B'].map(dict(zip(names, values))))
Output:
A B C
0 1 a T
1 2 b F
2 3 c F
3 4 d T
4 5 e G
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论