我想在数据框的“名称”列中添加特定股票的名称。
数据框由股票数据集的典型列组成:日期,价格等。最后是"name"
列,当前该列一直都填充有字符串“ name”。
我已经创建了一个行情清单(股票名称)列表,既作为列表又作为数据框(以最容易使用的形式)。有505只股票。
*每个部分(即每只股票的数据)长5314行(因为我有每日数据,所以是天数)。***
我的目标是以某种方式将这支木棍名称列表添加到与每种股票的板块相对应的“名称”列中。
数据框按字母顺序排序,我的股票行情清单也是如此。
我认为我应该做类似的事情; 将代码1向下追加到5314行 在接下来的5314行中追加代码2。 ..... 等等。
这就是我所拥有的:
这就是我想要的:
暂时忽略列顺序的更改。不确定为什么合并文件时它们会更改...
df
shareholders_equity tot_capital_risk working_capital name
2676424 2317.0 NaN 3297.0 name 2676425 2317.0 NaN 3297.0 name 2676426 2317.0 NaN 3297.0 name 2676427 2317.0 NaN 3297.0 name 2676428 2317.0 NaN 3297.0 name
编辑:我刚刚发现,单个股票的不同CSV文件(以及不同部分)的长度不相等。一些是5314行,一些是5311行,其他是5315等。 我现在该如何解决?
答案 0 :(得分:0)
如何?
t=0
i=1
for index df.index.values:
#set Name column of current row equal to the ticker in your ticker list at index t
df.at[index, 'Name']=list_of_tickers[t]
#skip to the next index of your ticker list when the number of iterations is a multiple of 5314
if i%5314==0:
t+=1 #increase the index of the ticker name list by one
i+=1
答案 1 :(得分:0)
df.loc[df.index%5314 == 0, 'name'] = list_of_tickers
df['name'] = df['name'].ffill()
ffill
将nan值替换为第一个非null值向上