我有一个如下所示的 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/