【发布时间】:2017-06-06 14:16:45
【问题描述】:
我正在构建函数来帮助我从网络加载数据。就加载数据而言,我试图解决的问题是列名因源而异。例如,Yahoo Finance 数据列标题如下所示 Open、High、Low、Close、Volume、Adj Close。 Quandl.com 将拥有包含 DATE、VALUE、date、value 等的数据集。全部大写和小写都会将所有内容以及 Value 和 Adj 排除在外。关闭在很大程度上意味着同样的事情。我想将具有不同名称但含义相同的列与一个值相关联。例如调整。收盘并看好两者 = AC;打开,打开,然后全部打开 = O。
所以我有一个 Csv 文件(“Functions//ColumnNameChanges.txt”),它存储 dict() 键和列名的值。
Date,D
Open,O
High,H
然后我写了这个函数来填充我的字典
def DictKeyValuesFromText ():
Dictionary = {}
TextFileName = "Functions//ColumnNameChanges.txt"
with open(TextFileName,'r') as f:
for line in f:
x = line.find(",")
y = line.find("/")
k = line[0:x]
v = line[x+1:y]
Dictionary[k] = v
return Dictionary
这是 print(DictKeyValuesFromText()) 的输出
{'': '', 'Date': 'D', 'High': 'H', 'Open': 'O'}
下一个函数是我的问题所在
def ChangeColumnNames(DataFrameFileLocation):
x = DictKeyValuesFromText()
df = pd.read_csv(DataFrameFileLocation)
for y in df.columns:
if y not in x.keys():
i = input("The column " + y + " is not in the list, give a name:")
df.rename(columns={y:i})
else:
df.rename(columns={y:x[y]})
return df
df.rename 不起作用。这是我得到的输出 print(ChangeColumnNames("Tvix_data.csv"))
The column Low is not in the list, give a name:L
The column Close is not in the list, give a name:C
The column Volume is not in the list, give a name:V
The column Adj Close is not in the list, give a name:AC
Date Open High Low Close Volume \
0 2010-11-30 106.269997 112.349997 104.389997 112.349997 0
1 2010-12-01 99.979997 100.689997 98.799998 100.689997 0
2 2010-12-02 98.309998 98.309998 86.499998 86.589998 0
列名应该是 D、O、H、L、C、V。我遗漏了一些东西,任何帮助将不胜感激。
【问题讨论】:
-
DF.rename本身并不是inplace操作。对于这两种情况,您都需要将这些更改分配回来,例如 -df.rename(..., inplace=True)。 -
成功了!!!完美!!
标签: python pandas dictionary dataframe