假設我創建了以下 df:
import pandas as pd
#column names
column_names = ["Time", "Currency", "Volatility expected", "Event", "Actual", "Forecast", "Previous"]
#create a dataframe including the column names
df = pd.DataFrame(columns=column_names)
然后,我創建以下陣列,其中包含要添加到我的單元格值df:
rows = ["2:00", "GBP", "", "Construction Output (MoM) (Jan)", "1.1%", "0.5%", "2.0%",
"2:00", "GBP", "", "U.K. Construction Output (YoY) (Jan)", "9.9%", "9.2%", "7.4%"]
那么,我怎樣才能使用 for 回圈來更新我的df,所以它最終是這樣的:
|Time |Currency |Volatility expected |Event |Actual |Forecast |Previous |
------------------------------------------------------------------------------------------------------------------
|02:00 |GBP | |Construction Output (MoM) (Jan) |1.1% |0.5% |2.0% |
|04:00 |GBP | |U.K. Construction Output (YoY) (Jan)|9.9% |9.2% |7.4% |
我試過了:
column_name_location = 0
for row in rows:
df.at['0', df[column_name_location]] = row
column_name_location = 1
print(df)
但得到:
關鍵錯誤:0
我可以在這里得到一些建議嗎?
uj5u.com熱心網友回復:
如果rows是專案的平面串列,您可以將其轉換為 numpy 陣列以先對其進行整形
假設rows實際上是一個子串列串列,每個子串列是一行,您可以pd.Series使用資料框的列名作為系列的索引從每一行創建一個,然后使用df.append將它們全部附加:
df.append([pd.Series(r, index=df.columns) for r in rows])
如果rows實際上只是一個平面串列,則需要將其轉換為 numpy 陣列以對其進行整形:
rows = np.array(rows).reshape(-1, 7).tolist()
uj5u.com熱心網友回復:
看起來您已經創建了一個包含 14 個專案的串列。您可以改為將其設為包含 2 個專案的串列,其中每個專案是一個包含 7 個值的串列。
rows = [["2:00", "GBP", "", "Construction Output (MoM) (Jan)", "1.1%", "0.5%", "2.0%"],
["2:00", "GBP", "", "U.K. Construction Output (YoY) (Jan)", "9.9%", "9.2%", "7.4%"]]
有了這個,我們可以直接創建一個資料框,如下所示
df = pd.DataFrame(rows, columns=column_names)
print(df)
這輸出 2 行
Time Currency Volatility expected Event Actual Forecast Previous
0 2:00 GBP Construction Output (MoM) (Jan) 1.1% 0.5% 2.0%
1 2:00 GBP U.K. Construction Output (YoY) (Jan) 9.9% 9.2% 7.4%
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/441203.html
標籤:python-3.x 熊猫 数据框 for循环 调试
上一篇:如果下載HTML時沒有出現URL,如何抓取它?Javascript在這里可能是個問題
下一篇:多鍵索引
