我在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
提交
取消