[英]How do I use dictionary keys and values to rename columns in a pandas DataFrame?
我正在構建功能來幫助我從Web加載數據。 就加載數據而言,我要解決的問題是列名稱因來源而異。 例如,Yahoo Finance數據列標題看起來像以下“打開”,“高”,“低”,“關閉”,“交易量”,“調整關閉”。 Quandl.com將具有包含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
可以正常工作,但是默認情況下它不在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)
好吧,當您已經將字典存儲在變量中時,說
DC = {'': '', 'Date': 'D', 'High': 'H', 'Open': 'O'}
DC現在可以映射到數據框列,例如
df.columns = df.columns.map(DC)
如果您想使用rename()方法,可以簡單地使用
df = df.rename(columns = DC)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.