根据另一列填充 pandas 列 [英] Filling a pandas column based on another column

查看:41
本文介绍了根据另一列填充 pandas 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据另一列中的条目填充数据框列的每一行,特别是我想用该股票的相应股票代码的相应名称填充每一行,就像这样

I would like to fill each row of a column of my dataframe based on the entries in another column, in particular I want to fill each row with the corresponding name of the corresponding ticker for that stock, like so

dict1 = [{'ticker': 'AAPL','Name': 'Apple Inc.'},
 {'ticker': 'MSFT','Name': 'Microsoft Corporation'}]

df1 = pd.DataFrame(dict1)

此函数提供给定代码的名称:

This function provides the name for a given ticker:

所以我可以为 MSFT 取名:

So I can pull the name for for say MSFT:

dict1 = [{'ticker': 'AAPL','Name': 'Apple Inc.'},
 {'ticker': 'MSFT','Name': get_nasdaq_symbols().loc['MSFT'].loc['Security Name'][:-15]}]

我正在努力寻找一种使用 for 循环或应用自动执行此操作的方法.任何人都可以建议一种方法吗?

I am struggling to find a way to automate this with a for loop or apply. Can anyone suggest an approach?

注意,用来拉取名字的函数来自这里:

Note, the function used to pull the name comes from here:

 from pandas_datareader.nasdaq_trader import get_nasdaq_symbols

推荐答案

可以先创建一个系列映射:

You can first create a series mapping:

ticker_name_map = get_nasdaq_symbols()['Security Name'].str[:-15]

然后使用pd.Series.地图1:

df1['Name'] = df1['ticker'].map(ticker_name_map)

如果您希望未映射的值保持不变,请使用后续的fillna:

If you wish unmapped values to remain unchanged, then use a subsequent fillna:

df1['Name'] = df1['ticker'].map(ticker_name_map).fillna(df1['Name'])

<小时>

1 pd.Series.replace 也是可能的,但是 低效.

这篇关于根据另一列填充 pandas 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆