我有一个数据框列表,其中每个都有不同的列,我想为所有列分配唯一的列名并将其组合起来,但它不起作用。有没有什么快速的方法可以在熊猫中做到这一点?
我的尝试
!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 个元素
我应该如何在熊猫中做到这一点?有什么快速的想法或技巧吗?谢谢
错误来自数据。几乎所有 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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句