0

你好,新年快乐 2018,

我有一些 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 函数的是名为 df_name 的 DataFrame,而不是具有 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'

太感谢了 !法比奥。

4

1 回答 1

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)

您可以将相同的内容放在多个数据帧的循环中以保存并保留更改名称。我希望这有帮助。

于 2018-01-05T14:54:39.723 回答