【发布时间】:2018-03-07 22:23:11
【问题描述】:
我需要根据 pandas 数据框的行索引将值插入到列中。
import pandas as pd
df=pd.DataFrame(np.random.randint(0,100,size=(11, 4)), columns=list('ABCD'))
df['ticker']='na'
df
Sample DataFrame 在上面的示例数据框中,记录总数的前 25% 的代码列必须具有值“$”,接下来 25% 的记录必须具有值“$$”,依此类推。
我尝试获取数据帧的长度并计算 25、50、75%,然后一次访问一行并根据行索引为“ticker”分配值。
total_row_count=len(df)
row_25 = int(total_row_count * .25)
row_50 = int(total_row_count * .5)
row_75=int(total_row_count*.75)
if ((row.index >=0) and (row.index<=row_25)):
return"$"
elif ((row.index > row_25) and (row.index<=row_50)):
return"$$"
elif ((row.index > row_50) and (row.index<=row_75)):
return"$$$"
elif (row.index > row_75):
return"$$$$"
但我无法获取行索引。如果有不同的方法来分配这些值,请告诉我
【问题讨论】: