且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从多个循环附加到数据框

更新时间:2023-09-13 17:12:10

IIUC您正在寻找的是:

IIUC what you are looking for is:

datanew=datanew.append({str(sizes)+';'+str(minute): pricediff}, ignore_index=True)

之所以会发生这种情况,是因为您不能在不修改整个数据帧长度的情况下更改数据帧单列的长度.

This happens because you cannot change length of a single column of a dataframe without modifying length of the whole data frame.

现在以下面的示例为例:

Now consider the below as an example:

import pandas as pd

df=pd.DataFrame({"a": list("xyzpqr"), "b": [1,3,5,4,2,7], "c": list("pqrtuv")})

print(df)

#this will fail:
#df["c"]=df["c"].append("abc", ignore_index=True)
#print(df)

#what you can do instead:
df=df.append({"c": "abc"}, ignore_index=True)

print(df)

#you can even create new column that way:
df=df.append({"x": "abc"}, ignore_index=True)

修改

为了附加pd.Series,请执行相同的操作:

In order to append pd.Series do literally the same:

abc=pd.Series([-1,-2,-3], name="c")
df=df.append({"c": abc}, ignore_index=True)

print(df)

abc=pd.Series([-1,-2,-3], name="x")
df=df.append({"x": abc}, ignore_index=True)