python - 如何使用字典键和值重命名Pandas DataFrame中的列?

标签 python pandas dictionary dataframe

我正在构建功能来帮助我从Web加载数据。就加载数据而言,我要解决的问题是列名称因来源而异。例如,Yahoo Finance数据列标题看起来像“打开”,“高”,“低”,“关闭”,“交易量”,“调整关闭”。 Quandl.com将具有包含DATE,VALUE,日期,值等的数据集。所有大写和小写字母将丢弃所有内容以及Value和Adj。关闭在大多数情况下是相同的意思。我想将名称不同但含义相同的列关联到一个值。例如调整。收盘价和值(value)均= 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=True。它期望使用旧名称作为键,而新名称作为值的字典。
df = df.rename({'col_a': 'COL_A', 'col_b': 'COL_B'})
或者
df.rename({'col_a': 'COL_A', 'col_b': 'COL_B'}, inplace=True)

关于python - 如何使用字典键和值重命名Pandas DataFrame中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41783176/

相关文章:

Python多线程不是并行执行的

Python MySQL 数据插入

python - 字典到直方图

python - 从txt文件生成pandas数据框

python - Pandas .DataFrame : How to align/group and sort data by index?

java - axis2 中的复杂类型 - map

python - 如何处理异常,同时在 python 中附加一个列表,其中包含从存储从 .json 文件读取的数据的字典中读取的数据?

python - 计算n维图像熵Python

python - 在本地和 Yarn 模式下运行 PySpark 的参数化 pytest fixture

python - 如何在 pandas 中将一组行洗牌在一起(行具有唯一的 id)