我有一些Python / Pandas DataFrame,每个都有不同的名称,我想根据用户的条目选择其中一个,并将其另存为.XLS文件。
我最初的悲惨代码:
import pandas as pd
path = 'C:\\Files\\'
def excel_save(df_name):
writer = pd.ExcelWriter(path +'some_name.xls')
shares.to_excel(writer,'Sheet1')
writer.save()
#Main
df_name=input ('Enter the name of the DataFrame to be saved as XLS ==>')
excel_save(df_name)
我要传递给excel_save函数的是DataFrame,其名称为df_name,而不是内容为df_name变量的字符串:
我想要保存AAPL DataFrame,而不是空白的东西或者AAPL'字符串。
我实际上是在和'exec'但还没有找到解决方案:
#Main
df_name=input ('Enetr the name of the DataFrame to be saved as XLS ==>')
excel_save(exec(df_name))
我也尝试过exec(' df_name')...到目前为止我没有雪茄
以下也没有用
start=dt.date(2017,12,1)
end=dt.date(2018,1,4)
AAPL = pdr.get_data_yahoo('AAPL', start, end)
AAPL.head()
Out[157]:
Open High Low Close Adj Close \
Date
2017-12-01 169.949997 171.669998 168.500000 171.050003 171.050003
2017-12-04 172.479996 172.619995 169.630005 169.800003 169.800003
2017-12-05 169.059998 171.520004 168.399994 169.639999 169.639999
2017-12-06 167.500000 170.199997 166.460007 169.009995 169.009995
2017-12-07 169.029999 170.440002 168.910004 169.320007 169.320007
Volume
Date
2017-12-01 39759300
2017-12-04 32542400
2017-12-05 27350200
2017-12-06 28560000
2017-12-07 25673300
df_name=input ('Enter the name of the DataFrame to be saved as XLS ==>')
Enter the name of the DataFrame to be saved as XLS ==>AAPL
df_name
Out[143]: 'AAPL'
final_path
Out[144]: 'C:\\0_Fabio\\Py Shares Data Manager\\Files\\some_name.xls'
df_name.to_excel(final_path)
Traceback (most recent call last):
File "<ipython-input-146-28a961de7a7e>", line 1, in <module>
df_name.to_excel(final_path)
AttributeError: 'str' object has no attribute 'to_excel'
非常感谢你!法比奥。
答案 0 :(得分:0)
据我所知,您希望选定的dataframe
文件以excel格式保存到特定路径。如果用户输入是dataframe
的名称,则可以直接保存dataframe
。
import pandas as pd
path = 'C:\\Files\\'
#main
df_name=input ('Enter the name of the DataFrame to be saved as XLS ==>')
final_path = path + "some_name.xls"
# Note : if type of df_name is just a string, you need to find corresponding data frame and then convert to excel.
df_name.to_excel(final_path)
您可以在多个数据帧的循环中将其保存并保留changine名称。 我希望这会有所帮助。