'_neg'
附加到原始变量名(库存位置)上。warehouse = pd.read_excel('warehouse.xls')
retail = pd.read_excel('retailonhand.xls')
shed3 = pd.read_excel('shed3onhand.xls')
tank1 = pd.read_excel('tank1onhand.xls')
tank2 = pd.read_excel('tank2onhand.xls')
all_stock_sites = [warehouse,retail,shed3,tank1,tank2]
all_neg_stock_sites = []
for site in all_stock_sites:
string_value_of_new_site = (pseudo code):'site-->string_value_of_site' + '_neg'
string_value_of_new_site = site[site.OnHand < 0]
all_neg_stock_sites.append(string_value_of_new_site)
# create new dataframes for each stock site's negative 'OnHand' values
warehouse_neg = warehouse[warehouse.OnHand < 0]
retail_neg = retail[retail.OnHand < 0]
shed3_neg = shed3[shed3.OnHand < 0]
tank1_neg = tank1[tank1.OnHand < 0]
tank2_neg = tank2[tank2.OnHand < 0]
'_neg'
的手。rglob
来自 pathlib
模块,以创建一个现有文件的列表f-strings
更新文件名AttributeError: 'DataFrame' object has no attribute 'OnHand'
),所以我们把代码放在 try-except
块。块。continue
语句,继续进行下一次循环迭代。_neg
添加到文件名中from pathlib import Path
import pandas as pd
# set path to top file directory
d = Path(r'e:\PythonProjects\stack_overflow\stock_sites')
# get all xls files
files = list(d.rglob('*.xls'))
# create, filter and save dict of dataframe
df_dict = dict()
for file in files:
# create dataframe
df = pd.read_excel(file)
try:
# filter df and add to dict
df = df[df.OnHand < 0]
except AttributeError as e:
print(f'{file} caused:\n{e}\n')
continue
if not df.empty:
df_dict[f'{file.stem}_neg'] = df
# save to new file
new_path = file.parent / f'{file.stem}_neg{file.suffix}'
df.to_excel(new_path, index=False)
print(df_dict.keys())
>>> dict_keys(['retailonhand_neg', 'shed3onhand_neg', 'tank1onhand_neg', 'tank2onhand_neg', 'warehouse_neg'])
# access individual dataframes as you would any dict
df_dict['retailonhand_neg']
我的建议是不要使用变量名作为数据的 "键",而是给它们分配合适的名字,用元组或dict。
因此,与其用:
warehouse = pd.read_excel('warehouse.xls')
retail = pd.read_excel('retailonhand.xls')
shed3 = pd.read_excel('shed3onhand.xls')
你可以用:
sites = {}
sites['warehouse'] = pd.read_excel('warehouse.xls')
sites['retail'] = pd.read_excel('retailonhand.xls')
sites['shed3'] = pd.read_excel('shed3onhand.xls')
...etc
然后你可以像这样创建负键。
sites_neg = {}
for site_name, site in sites.items():
neg_key = site_name + '_neg'
sites_neg[neg_key] = site[site.OnHand < 0]