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

查看:93
本文介绍了根据另一列填充 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.map 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 也可以,但是效率低.


1 pd.Series.replace is also possible, but inefficient.

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

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