簡體   English   中英

如何使用pandas / python將變量值放在列表的其他列表中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM