我在txt 文件中有数据,我将其转换为数据帧(data3),我将索引重命名为从 -6 到 +5,现在,在 for 循环中,我想使用访问数据帧的特定值iloc 命令,但我没有得到正确的值。数据框看起来像这样如果我使用 data3.iloc[-6,1] 我期望返回值 = -6 但相反,我得到 -20data3.iloc[-5,1] 我原本期待=-20,但结果却是-6data3.iloc[-4,1] 我原以为 = -28 但结果是 -7有人可以帮我吗?将索引保留在 -6 到 +5 之间对我来说很重要这是我的代码。谢谢import numpy as npimport pandas as pddata= pd.read_csv('perfilprueba.txt',delimiter=' ')## This is because when I read the txt doesnt read dist and amp as diferent columnsdata_drop = data.drop(data.columns[[1, 2, 3, 4, 6,7]], axis=1) data2=data_drop.rename(columns={"Unnamed: 5": "amp"})## These are two index I will use laterm=int(round(len(data2.index)))n=int(round(m/2))## This is because I wanted that my data had index values from -6 to 5+ AND## also a column with values from -6 to +5r = pd.Series(np.linspace(-n, n-1,m)) data2['r'] = r erre = pd.Series(np.linspace(-n, n-1,m)) data2['erre']=erre data3=data2.set_index('r')## Now I want to run a for loop## that returns me the values of the "amp" column as r moves from -6 to +5ap=[]for r in range(-n,n): a = data3.loc[[r],['amp']] ap += [a]
2 回答
凤凰求蛊
TA贡献1825条经验 获得超4个赞
pandas.DataFrame.iloc
是“基于纯整数位置的索引,用于按位置选择”,这意味着当您调用 时data3.iloc[-5, 1]
,您实际上是从数据帧末尾的第五行的第二列中获取。
在你的情况下,我会使用pandas.DataFrame.at
,尽管在这种情况下,你也可以使用pandas.DataFrame.loc
.
该脚本如下所示:
# reading the data (the "sep=\s+" parameter does what is needed)
data3 = pd.read_csv('perfilprueba.txt', sep="\s+")
m = int(round(len(data3.index)))
n = int(round(m/2))
# changing the index so it starts at -n
data3.index -= n
data3['erre'] = data3.index
ap = []
for r in range(-n,n):
# note that you have to use the column name here
a = data3.at[r,"amp"]
ap.append(a)
添加回答
举报
0/150
提交
取消