首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >通过另外两列更新pandas

通过另外两列更新pandas
EN

Stack Overflow用户
提问于 2021-05-07 01:38:14
回答 1查看 37关注 0票数 1

我有一个大约有3000个条目和10列的数据集,所以这是一个简单得多的版本

代码语言:javascript
运行
复制
df =
   asset    tail    more_info
0   x         a     this is a long text field that is right
1   x         b     this is a long text field that is almost right
2   y         a     this is right
3   y         b     this is probably not right

期望的结果

代码语言:javascript
运行
复制
df =
   asset    tail    more_info
0   x         a     this is a long text field that is right
1   x         b     this is a long text field that is right
2   y         a     this is right
3   y         b     this is right

所以我正在尝试更新我的more_info字段,其中资产匹配并且尾部等于'a‘实际上数据集更复杂,所以我需要通过编程来完成,这就是我在该逻辑中空白的地方

代码语言:javascript
运行
复制
def my_func(x):
    if x.asset == x.asset and x.tail =='b':
        '''
        this would be where I'd set it to x.more_info where tail = 'a' maybe numpy where ??
        '''
        
df['more_info'] = df['more_info'].apply(lambda x: my_func(x))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-07 01:54:42

您可以尝试这样做:

代码语言:javascript
运行
复制
# reduce dataframe to contain only
df1 = df[['asset', 'tail']].copy()

# slice df to get only the ones you want to use for "more_info"
df2 = df[df['tail']=='a'][['asset', 'more_info']].copy()

df1.merge(df2, on=['asset'])

#   asset tail                                more_info
# 0     x    a  this_is_a_long_text_field_that_is_right
# 1     x    b  this_is_a_long_text_field_that_is_right
# 2     y    a                            this_is_right
# 3     y    b                            this_is_right

或者一行:

代码语言:javascript
运行
复制
df[['asset', 'tail']].merge(df[df['tail']=='a'][['asset', 'more_info']], on=['asset'])
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67423340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档