如何:在 for 循环中,每次在同一行中按名称在特定列插入值。所以我有几百列。我希望每个值都放在适当列的同一行(使用日期)上。这是我的数据框列:
DATE, ABC, BGF, ATR
这是我对 List
的示例值:
[["VAL:ABC", 5, 6, 7], ["VAL:ATR", 7, 43]]
这是我的数据框的行为方式,将具有匹配第一个元素的列表放入新行的数据框中。
<块引用>DATE, ABC, BGF, ATR
12-01-2011 5 - -
仍然在同一行上,将具有相同列标题的下一个列表项放入。
<块引用>DATE, ABC, BGF, ATR
12-01-2011 5 - 7
这是我目前的代码
mod_df = df.append({'Date' : str(currentDate)}, ignore_index=True)
# append new values
for col in df.columns:
#print(col)
for aMrket in List_market_data: # [["VAL:ABC", 5, 6, 7], ["VAL:ATR", 7, 43]]
if aMrket[1] == str(col):
# if column header is the same as the last 3 characters in the list's first item
# then add to same row (use the date)
mod_df.loc[mod_df.Date == currentDate, col] = aMrket[-3]
上面的最后一行代码是我想要的。我明白了
答案 0 :(得分:0)
编辑特定的 ROW (mod_df.Date)
仅在出现特定值的地方 (== currentDate),
在col(, col)上
使用这个值 (= aMrket[-3])
mod_df.loc[mod_df.Date == currentDate, col] = aMrket[-3]