Mik*_*ico 109
有时候在熊猫之外做所有附加操作会更容易,然后,只需一次创建DataFrame即可.
>>> import pandas as pd
>>> simple_list=[['a','b']]
>>> simple_list.append(['e','f'])
>>> df=pd.DataFrame(simple_list,columns=['col1','col2'])
col1 col2
0 a b
1 e f
Run Code Online (Sandbox Code Playgroud)
Ash*_*yan 65
df = pd.DataFrame(columns=list("ABC"))
df.loc[len(df)] = [1,2,3]
Run Code Online (Sandbox Code Playgroud)
Jai*_*nde 56
这是一个简单而愚蠢的解决方案:
>>> import pandas as pd
>>> df = pd.DataFrame()
>>> df = df.append({'foo':1, 'bar':2}, ignore_index=True)
Run Code Online (Sandbox Code Playgroud)
Ale*_*ord 32
你能做这样的事吗?
>>> import pandas as pd
>>> df = pd.DataFrame(columns=['col1', 'col2'])
>>> df = df.append(pd.Series(['a', 'b'], index=['col1','col2']), ignore_index=True)
>>> df = df.append(pd.Series(['d', 'e'], index=['col1','col2']), ignore_index=True)
>>> df
col1 col2
0 a b
1 d e
Run Code Online (Sandbox Code Playgroud)
有没有人有更优雅的解决方案?
Jay*_*arm 24
关于Mike Chirico的回答......如果你想在数据框已经填充之后附加一个列表......
>>> list = [['f','g']]
>>> df = df.append(pd.DataFrame(list, columns=['col1','col2']),ignore_index=True)
>>> df
col1 col2
0 a b
1 d e
2 f g
Run Code Online (Sandbox Code Playgroud)
有几种方法可以在 Python 中将列表附加到 Pandas 数据帧。让我们考虑以下数据框和列表:
import pandas as pd
# Dataframe
df = pd.DataFrame([[1, 2], [3, 4]], columns = ["col1", "col2"])
# List to append
list = [5, 6]
Run Code Online (Sandbox Code Playgroud)
选项 1:将列表附加到数据帧的末尾?pandas.DataFrame.loc.
df.loc[len(df)] = list
Run Code Online (Sandbox Code Playgroud)
选项 2:将列表转换为数据框并附加?pandas.DataFrame.append().
df = df.append(pd.DataFrame([list], columns=df.columns), ignore_index=True)
Run Code Online (Sandbox Code Playgroud)
选项 3:将列表转换为系列并附加??pandas.DataFrame.append()?.
df = df.append(pd.Series(list, index = df.columns), ignore_index=True)
Run Code Online (Sandbox Code Playgroud)
上述每个选项都应输出如下内容:
>>> print (df)
col1 col2
0 1 2
1 3 4
2 5 6
Run Code Online (Sandbox Code Playgroud)
参考:如何将列表作为一行附加到 Python 中的 Pandas DataFrame?
小智 6
在 append 函数中将列表转换为数据框也有效,在循环中应用时也是如此
import pandas as pd
mylist = [1,2,3]
df = pd.DataFrame()
df = df.append(pd.DataFrame(data[mylist]))
Run Code Online (Sandbox Code Playgroud)
这是一个函数,给定一个已经创建的数据帧,它将添加一个列表作为一个新行。这可能应该包含错误捕获器,但是如果您确切地知道要添加的内容,那么这应该不是问题。
import pandas as pd
import numpy as np
def addRow(df,ls):
"""
Given a dataframe and a list, append the list as a new row to the dataframe.
:param df: <DataFrame> The original dataframe
:param ls: <list> The new row to be added
:return: <DataFrame> The dataframe with the newly appended row
"""
numEl = len(ls)
newRow = pd.DataFrame(np.array(ls).reshape(1,numEl), columns = list(df.columns))
df = df.append(newRow, ignore_index=True)
return df
Run Code Online (Sandbox Code Playgroud)