python - Pandas - 两列作为索引(有效时间和行号)?

标签 python pandas csv

我有一个如下所示的 csv

valid,value
2004-07-21 09:00:00,200
2004-07-21 10:00:00,200
2004-07-21 11:00:00,150

必须将有效列设置为这样的索引

import pandas as pd
df = pd.read_csv('test.csv')
df['valid'] = pd.to_datetime(df['valid'])  # convert 'valid' column to pd.datetime objects
df = df.set_index('valid')  # set the 'valid' as index

我仍然希望能够通过行索引访问数据,但是像这样

for row_index in range(len(df)):  # I know iterating over a df is not avisable
    print(df.at[row_index])

但是我收到一个错误。 ValueError:基于非整数索引的索引只能有非整数索引器

我肯定必须有有效的列作为索引。但是我怎样才能打印给定索引的行呢?

最佳答案

更改按标签选择:

print(df.at[row_index])

通过位置选择,选择第一列 DataFrame.iat :

for row_index in range(len(df)):  # I know iterating over a df is not avisable
    #convert position of value column to 0  
    print(df.iat[row_index, df.columns.get_loc('value')])
    #selecting first column - 0
    #print(df.iat[row_index, 0])
200
200
150

或者使用DataFrame.iloc :

for row_index in range(len(df)):  # I know iterating over a df is not avisable
    print(df.iloc[row_index])

value    200
Name: 2004-07-21 09:00:00, dtype: int64
value    200
Name: 2004-07-21 10:00:00, dtype: int64
value    150
Name: 2004-07-21 11:00:00, dtype: int64

区别在于 iat 更快,但返回交集索引/列值 - 标量,但 iloc 更通用,这里将所有列返回到系列 - 系列名称是索引value,Series的索引值为列名。

关于python - Pandas - 两列作为索引(有效时间和行号)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59405500/

相关文章:

python - EMR Spark 附加到 parquet 文件的步骤是覆盖 parquet 文件

python 3 : How to write a __iter__ method for derived class so that it extends on the behaviour of the base class' __iter__ method

python - 使用Python SDK部署ARM模板权限不足

python - 没有文件更改数据的 merge 提交无法在数据框中显示

Python CSV,如何在逐行(逐行)读取数据的同时将数据追加到行尾?

ruby - 如何使用 Logstash 配置文件将 Logstash 中的字段设置为 "not_analyzed"

python - 在 python 中迭代大型 CSV 文件时如何轻松内存?

Python:对象作为另一个对象的参数

python - 反转数据框中的行值

python - 在 Pandas 中创建层次结构列