[英]Create a dataframe on incremental basis
I'm writing a code whose end result is a dataframe.我正在编写一个代码,其最终结果是一个数据帧。 This dataframe will be created on incremental basis.此数据框将在增量的基础上创建。 I read that the recommended approach to accomplish this is to create a list of list and at the end convert it into a dataframe.我读到推荐的方法是创建一个列表列表,最后将其转换为数据帧。 Below are major steps以下是主要步骤
dfColumns = ["ColA", "ColB", "ColC", "ColD"]
lst = []
for i in range(5):
ColA = something
ColB = something
ColC = something
ColD = something
lst.append([ColA, ColB, ColC, ColD])
df = pd.DataFrame(lst, columns=dfColumns)
I am looking for a way such that I dont have to write ColA, ColB.... at 3 places.我正在寻找一种方法,这样我就不必在 3 个地方写 ColA、ColB ....。 Is there a way to do something like this lst.append(dfColumns)
有没有办法做这样的事情lst.append(dfColumns)
You can create a DataFrame
from a list of dictionaries:您可以从字典列表中创建一个DataFrame
:
import pandas
column_names = ["ColA", "ColB", "ColC", "ColD"]
rows = []
for _ in range(5):
# Explicitly create the row content
row = {
"ColA": "something",
"ColB": "something",
"ColC": "something",
"ColD": "something",
}
# OR
# Dynamically create each column from the column names
row = {key: "something" for key in column_names}
# Add the row to the list
rows.append(row)
# Create a dataframe from a list of dicts will automatically find the column names
df = pandas.DataFrame(rows)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.