Pandas:使用列表更新多行

huangapple go评论62阅读模式
英文:

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

你可以使用布尔索引结合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)))

效率较低的替代方法:

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

huangapple
  • 本文由 发表于 2023年6月19日 15:07:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定