gpt4 book ai didi

python - 如何检查pandas中另一个数据框中是否存在值?

转载 作者:行者123 更新时间:2023-12-01 01:38:15 25 4
gpt4 key购买 nike

我下面有一个数据框,其中包含法语到英语之间的映射

df1 

french english
ksjks an
sjk def
ssad sdsd

另一个数据框列是法语,因此需要使用 df1 将它们转换为英语

df2

ksjks sjk ssad
2 4 6

我们怎样才能实现这一目标?

new_cols = []
for col in df2.columns:
if col in df1['french']:
how to get corresponding english value

PS:刚刚放入随机数据作为样本

最佳答案

选项 1
mapset_index 结合使用

df2.columns = df2.columns.map(df1.set_index('french').english)
print(df2)

选项 2
renameset_index 结合使用:

df2.rename(columns=df1.set_index('french').english.to_dict())

两者都产生:

   an  def  sdsd
0 2 4 6

列的顺序并不重要:

df1 = pd.DataFrame({'french': ['un', 'deux', 'trois'], 'english': ['one', 'two', 'three']})
df2 = pd.DataFrame([[1,2,3]], columns=['trois', 'deux', 'un'])

df2.rename(columns=df1.set_index('french').english.to_dict())

three two one
0 1 2 3

df2.columns.map(df1.set_index('french').english)
# Index(['three', 'two', 'one'], dtype='object')

关于python - 如何检查pandas中另一个数据框中是否存在值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52176478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com