Python 熊猫-将列表附加到现有数据帧,顺序与列相同
好的,我有一个预创建的数据帧,我尝试向它附加一个列表。在简化版本中,问题如下Python 熊猫-将列表附加到现有数据帧,顺序与列相同,python,pandas,dataframe,Python,Pandas,Dataframe,好的,我有一个预创建的数据帧,我尝试向它附加一个列表。在简化版本中,问题如下 df = pd.DataFrame({'One': [], 'Another' : [], 'Third' : [], 'Last' : []}) 然后我用列表做了一些事情: new_obj = [] new_obj.append('1') new_obj.append('2') #I have to do the ext
df = pd.DataFrame({'One': [],
'Another' : [],
'Third' : [],
'Last' : []})
然后我用列表做了一些事情:
new_obj = []
new_obj.append('1')
new_obj.append('2')
#I have to do the extend operation here
new_obj.extend(['3','4'])
现在我只想将我的new_obj
列表添加到我的数据帧中,对象的顺序与我在数据帧中想要的顺序相同
所以我只想:
df.loc[len(df.index)] = new_obj
因此,我:
Another Last One Third
0 1 2 3 4
为什么?!为什么它会将列顺序更改为非固定顺序。追加时如何保存?您的行df.loc[len(df.index)]=new_obj
没有更改列的顺序
字典键是无序的,因此当您将字典传递给pd.DataFrame()以创建数据帧时,列不一定按照您编写它们的顺序
请尝试以下操作以确认:
df = pd.DataFrame({'One': [],
'Another' : [],
'Third' : [],
'Last' : []})
df.columns
索引(['other','Last','One','Third'],dtype='object')
…如果您关心列的顺序,请按如下方式初始化df:
columns = ['one', 'another', 'third', 'last']
df = pd.DataFrame(columns=columns)
请注意,Python中的
dict
本质上是无序的。为了为数据帧指定正确的顺序,您可以编写(或用户集合。OrderedDict
):
另一方面,如果您并不真正关心数据框中的顺序
,您只需简单地使用dict
即可在列表
中明确定义要添加的列:
new_obj = {"One" : 1, "Anohter" : 2, "Third" : 3, "Last" : 4}
df.loc[len(df.index)] = new_obj
正如其他答案所提到的,听写键没有顺序。如果您想使用orderddict,请使用orderddict,如下所示
import pandas as pd
import collections
mydict = collections.OrderedDict((('One', []),
('Another', []),
('Third', []),
('Last', [])))
df = pd.DataFrame.from_dict(mydict)
new_obj = []
new_obj.append('1')
new_obj.append('2')
#I have to do the extend operation here
new_obj.extend(['3','4'])
df.loc[len(df.index)] = new_obj
print df
导致
One Another Third Last
0 1 2 3 4
与参数一起使用ignore\u index=True
df = pd.DataFrame(columns='One Another Third Last'.split())
new_obj = []
new_obj.append('1')
new_obj.append('2')
#I have to do the extend operation here
new_obj.extend(['3','4'])
# notice I created a `pd.Series` with `df.columns` as the index
df.append(pd.Series(new_obj, df.columns), ignore_index=True)
One Another Third Last
0 1 2 3 4
df = pd.DataFrame(columns='One Another Third Last'.split())
new_obj = []
new_obj.append('1')
new_obj.append('2')
#I have to do the extend operation here
new_obj.extend(['3','4'])
# notice I created a `pd.Series` with `df.columns` as the index
df.append(pd.Series(new_obj, df.columns), ignore_index=True)
One Another Third Last
0 1 2 3 4