![](/img/trans.png)
[英]How to save multiple values on different rows as a variable or list in a CSV using Python Pandas
[英]How to put variable values in the other list of list using pandas/python
我有两个变量:
date = 2018-10-25
因为所有日期都被存储
df =[['Euro', 0.8762059999999999], ['British Pound', 0.7755920000000001], ['Indian Rupee', 73.246211], ['Australian Dollar', 1.4093959999999999], ['Canadian Dollar', 1.308288], ['Singapore Dollar', 1.379124], ['Swiss Franc', 0.999036], ['Malaysian Ringgit', 4.1631849999999995], ['Japanese Yen', 112.293159], ['Chinese Yuan Renminbi', 6.944638]]
像清单清单一样。
我想要输出: [['Euro',2018-10-25, 0.8762059999999999],['British Pound', 2018-10-25, 0.7755920000000001],['Indian Rupee',2018-10-25, 73.246211],....]
像这样使用pandas / python for循环使用列表中的所有元素。
并希望将其存储在Mysql数据库中,那么它的查询如何进行?
因此,请帮助指导我该怎么办。 我尝试了这个但是没有用:
total = []
for i in df:
total = [df[0][0], date, df[0][1]]
超级简单:
date = "2018-10-25"
df =[['Euro', 0.8762059999999999], ['British Pound', 0.7755920000000001], ['Indian Rupee', 73.246211], ['Australian Dollar', 1.4093959999999999], ['Canadian Dollar', 1.308288], ['Singapore Dollar', 1.379124], ['Swiss Franc', 0.999036], ['Malaysian Ringgit', 4.1631849999999995], ['Japanese Yen', 112.293159], ['Chinese Yuan Renminbi', 6.944638]]
// Loop through df, i being the position, and append the date to the end of each
// of those arrays under df, because df is a multi dimensional array.
for i in df:
i.insert(1,date)
print(df)
尝试这个:
date = '2018-10-25'
for i in df:
i.insert(1,date)
In [1154]: df
Out[1154]:
[['Euro', '2018-10-25', 0.8762059999999999],
['British Pound', '2018-10-25', 0.7755920000000001],
['Indian Rupee', '2018-10-25', 73.246211],
['Australian Dollar', '2018-10-25', 1.4093959999999999],
['Canadian Dollar', '2018-10-25', 1.308288],
['Singapore Dollar', '2018-10-25', 1.379124],
['Swiss Franc', '2018-10-25', 0.999036],
['Malaysian Ringgit', '2018-10-25', 4.1631849999999995],
['Japanese Yen', '2018-10-25', 112.293159],
['Chinese Yuan Renminbi', '2018-10-25', 6.944638]]
现在,您可以从上方创建一个dataframe
以插入到Mysql
frame = pd.DataFrame(df)
frame.columns = ['Currency' ,'date', 'value']
frame.date = frame.date.apply(pd.to_datetime)
In [1156]: frame
Out[1156]:
0 1 2
0 Euro 2018-10-25 0.876206
1 British Pound 2018-10-25 0.775592
2 Indian Rupee 2018-10-25 73.246211
3 Australian Dollar 2018-10-25 1.409396
4 Canadian Dollar 2018-10-25 1.308288
5 Singapore Dollar 2018-10-25 1.379124
6 Swiss Franc 2018-10-25 0.999036
7 Malaysian Ringgit 2018-10-25 4.163185
8 Japanese Yen 2018-10-25 112.293159
9 Chinese Yuan Renminbi 2018-10-25 6.944638
from pandas.io import sql
import MySQLdb
frame.to_sql(con=con, name='table_name', if_exists='replace', flavor='mysql', index=False)
让我知道它是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.