【问题标题】:How to access to a specific values in a dataframe based on the index values using loc[i,j]如何使用 loc[i,j] 根据索引值访问数据框中的特定值
【发布时间】:2021-01-29 12:44:21
【问题描述】:

我在 txt file 中有数据,我将其转换为数据帧 (data3),我将索引重命名为从 -6 运行到 +5,现在,在 for 循环中,我想访问特定值使用 iloc 命令的数据帧,但我没有得到正确的值。

The dataframe looks like this

如果我使用 data3.iloc[-6,1],我期望返回值 = -6,但结果却是 -20

data3.iloc[-5,1] 我期待 =-20,但结果却是 -6

data3.iloc[-4,1] 我期待 = -28 但我得到了 -7

有人可以帮帮我吗?将索引从 -6 保留到 +5 对我来说很重要 这是我的代码。谢谢

import numpy as np
import pandas as pd


data= pd.read_csv('perfilprueba.txt',delimiter=' ')

## This is because when I read the txt doesnt read dist and amp as diferent 
columns
data_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 later
m=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 +5

r = 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 +5

ap=[]
for r in range(-n,n):
     a = data3.loc[[r],['amp']]
     ap   += [a]

【问题讨论】:

    标签: python pandas for-loop indexing


    【解决方案1】:

    pandas.DataFrame.iloc 是“用于按位置选择的纯整数位置索引”(来自doc),这意味着当您调用data3.iloc[-5, 1] 时,您实际上是从第 5 行的第二列中获取数据框的结尾。

    在你的情况下,我会使用pandas.DataFrame.at(文档here),但在这种情况下,你也可以使用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)
    

    【讨论】:

      【解决方案2】:

      按整数位置访问行/列对的单个值。
      Documentation ap=[] 对于范围内的 r(-n,n): a = data3.loc[r].iat1 ap += [a]

      【讨论】:

        猜你喜欢
        • 2020-03-23
        • 2018-02-12
        • 2021-08-19
        • 2021-01-05
        • 1970-01-01
        • 2016-09-28
        • 1970-01-01
        • 2013-11-19
        • 2022-12-09
        相关资源
        最近更新 更多