我有資料框串列,其中每個都有不同的列,我想為所有列分配唯一的列名并將其組合,但它不起作用。有沒有什么快速的方法可以在熊貓中做到這一點?
我的嘗試
!pip install wget
import wget
import pandas as pd
url = 'https://github.com/adamFlyn/test_rl/blob/main/test_data.xlsx'
data= wget.download(url)
xls = pd.ExcelFile('~/test_data.xlsx')
names = xls.sheet_names[1:]
# iterate to find sheet name that matches
data_dict = pd.read_excel(xls, sheet_name = [name for name in xls.sheet_names if name in names])
dfs=[]
for key, val in data_dict.items():
val['state_abbr'] = key
dfs.append(val)
for df in dfs:
st=df.columns[0]
df['state']=st
df.reset_index()
for df in dfs:
lst=df.columns.tolist()
lst=['county','orientation','state_abbr','state']
df.columns=lst
final_df=pd.concat(dfs, axis=1, inplace=True)
但我無法像這樣重命名每個資料幀的名稱并出現此錯誤:
for df in dfs:
lst=df.columns.tolist()
lst=['county','orientation','state_abbr','state']
df.columns=lst
ValueError:長度不匹配:預期軸有 5 個元素,新值有 4 個元素
我應該如何在熊貓中做到這一點?有什么快速的想法或技巧嗎?謝謝
uj5u.com熱心網友回復:
錯誤來自資料。幾乎所有 DataFrames 表都有 3 列,但只有“NC”有一個以“未命名”開頭的冗余列,除了一行具有"`"值外,幾乎所有的都是 NaN。如果我們從該表中洗掉該列,則其余代碼將按預期作業。
您可以在字典理解中使用assign和更改列名來分配新列。set_axis此外,您可以使用names自身,而不是串列理解來獲取作業表名稱。最后,簡單地將所有與concat.
out = pd.concat([df.loc[:, ~df.columns.str.startswith('Unnamed')]
.set_axis(['county','orientation'], axis=1)
.assign(state=df.columns[0], state_abbr=k)
for k, df in pd.read_excel(xls, sheet_name = names).items()])
輸出:
county orientation state state_abbr
0 Aleutians East Plaintiff Alaska AK
1 Aleutians West Plaintiff Alaska AK
2 Anchorage Neutral Alaska AK
3 Bethel Plaintiff Alaska AK
4 Bristol Bay Plaintiff Alaska AK
.. ... ... ... ...
18 Sweetwater Neutral Wyoming WY
19 Teton Neutral Wyoming WY
20 Uinta Defense Wyoming WY
21 Washakie Defense Wyoming WY
22 Weston Defense Wyoming WY
[3117 rows x 4 columns]
uj5u.com熱心網友回復:
在這里,當你運行reset_index()它時,它實際上并沒有就地做任何事情。
for df in dfs:
st=df.columns[0]
df['state']=st
df.reset_index() # <----- returns df with reset index, but is not assigned.
uj5u.com熱心網友回復:
您應該將 df.columns=lst 移出回圈
for df in dfs:
lst=df.columns.tolist()
lst=['county','orientation','state_abbr','state']
df.columns=lst
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/467205.html
標籤:Python python-3.x 擅长 熊猫 数据框
上一篇:如何為虛擬環境設定pip配置?
下一篇:迭代器反轉for回圈的執行順序?
