逐行循环遍历 Pandas 数据帧,并将数据帧的值作为文件名的一部分
我正在尝试导出数据帧的每一行以生成单独的 csv 文件。我创建了一个循环来遍历每一行。文件名将是相应行的货币值+当前日期作为文件名。我的数据框中有 4 行,预计有四个 csv 文件输出。例如,对于 GBP,结果应生成类似“GBP_20220326.csv”的文件名,并且 csv 文件内容将具有两个值“GBP,1.232”。
关于如何获取货币值(例如,英镑作为文件名的一部分),我对如何获取货币值感到困惑。如果有人能给我一些指导,我将不胜感激,非常感谢。
>import numpy as np
>import pandas as pd
>from datetime import datetime
>rate = {"Currency":["EUR","GBP","JPY","AUD"],
"Rate":[1.11,1.232,120,0.73],
}
>df = pd.DataFrame(rate)
>df
>for i in range(0, len(df)):
> df.iloc[i:i+1].to_csv(df.iloc[0] + datetime.now().strftime("%Y%m%d") + '.csv', index=False, header=True)
#这最后一行没有按计划工作。
I am trying to export each row of a dataframe to generate separate csv files. I created a loop to go through each row. The file name will be the currency value of the respective row + the current date as the file name. I have 4 rows in the dataframe and expect to have four csv file outputs. For example, for GBP, the result should generate the file name like "GBP_20220326.csv" and the csv file content will have two values "GBP,1.232".
I am stuck with one point on how to get the currency value (e.g. GBP to be part of the file name. Greatly appreciated if anyone can give me some guidance on this, many thanks.
>import numpy as np
>import pandas as pd
>from datetime import datetime
>rate = {"Currency":["EUR","GBP","JPY","AUD"],
"Rate":[1.11,1.232,120,0.73],
}
>df = pd.DataFrame(rate)
>df
>for i in range(0, len(df)):
> df.iloc[i:i+1].to_csv(df.iloc[0] + datetime.now().strftime("%Y%m%d") + '.csv', index=False, header=True)
#This last line was not working as planned.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用 df.iterrows:
输出:
Try using
df.iterrows
:Output: