Python:使用pandas读取txt文件时出错

2024-06-24 13:04:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个txt文件“TempData.txt文件“格式如下:

CODE    O/F Valid Date  MAX MIN AVG
K3T5    O   1995/01/01  51  36  44
K3T5    O   1995/01/02  45  33  39
K3T5    O   1995/01/03  48  38  43

我正在尝试创建一个包含“ValidDates”、“Max”和“Min”元素的字典。你知道吗

我正在尝试以下方法:

import pandas as pd
df = pd.read_csv(r'C:\TempData.txt', sep = "\t", header = 0)

df.columns.tolist() #prints: 'CODE', 'O/F', 'Valid Date', 'MAX', 'MIN', 'AVG'
Max = df([4])

尝试分离最大列时出现错误:

TypeError: 'DataFrame' object is not callable

Tags: 文件txtdfdate格式codeminmax
1条回答
网友
1楼 · 发布于 2024-06-24 13:04:59

我想你可以用:

max_col = df['MAX']

print (max_col)
0    51
1    45
2    48
Name: MAX, dtype: int64

如果要选择4.列,请使用^{}

max_col = df.iloc[:, 3] #3, because python counts 0,1,2,3

print (max_col)
0    51
1    45
2    48
Name: MAX, dtype: int64

首先,可以省略header=0,因为它是^{}中的默认值,并添加parse_dates,用于将Valid Date转换为datetime。你知道吗

如果需要dictValid DateMAXMIN列使用^{},如果需要不同格式的dict,请尝试添加参数orient

df = pd.read_csv(r'C:\TempData.txt', sep = "\t", parse_dates=[2])
print (df)
   CODE O/F Valid Date  MAX  MIN  AVG
0  K3T5   O 1995-01-01   51   36   44
1  K3T5   O 1995-01-02   45   33   39
2  K3T5   O 1995-01-03   48   38   43


print (df[['Valid Date','MAX','MIN']])
  Valid Date  MAX  MIN
0 1995-01-01   51   36
1 1995-01-02   45   33
2 1995-01-03   48   38

print (df[['Valid Date','MAX','MIN']].to_dict())
{'MAX': {0: 51, 1: 45, 2: 48}, 
'MIN': {0: 36, 1: 33, 2: 38}, 
'Valid Date': {0: Timestamp('1995-01-01 00:00:00'), 1: Timestamp('1995-01-02 00:00:00'), 2: Timestamp('1995-01-03 00:00:00')}}

print (df[['Valid Date','MAX','MIN']].to_dict(orient='split'))
{'data': [['1995/01/01', 51, 36], ['1995/01/02', 45, 33], ['1995/01/03', 48, 38]], 'index': [0, 1, 2], 'columns': ['Valid Date', 'MAX', 'MIN']}

相关问题 更多 >