Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将多个列(不存在)添加到dataframe的行中_Python_Pandas - Fatal编程技术网

Python 将多个列(不存在)添加到dataframe的行中

Python 将多个列(不存在)添加到dataframe的行中,python,pandas,Python,Pandas,请使用此代码 a = pd.DataFrame([1,2,3]) 如果我这样做 a.loc[0,'A']=3 我得到: 0 A 0 1 3 1 2 NaN 2 3 NaN 现在假设: a = pd.DataFrame([1,2,3]) b=pd.DataFrame([[5,4],[6,3],[7,2]],columns=['B','C']) 有没有一种方法可以执行a[1,'a','B']=B[2],从而得到结果 0 B C 0 1 NaN NaN 1

请使用此代码

a = pd.DataFrame([1,2,3])
如果我这样做

a.loc[0,'A']=3
我得到:

   0   A
0  1   3
1  2 NaN
2  3 NaN
现在假设:

a = pd.DataFrame([1,2,3])
b=pd.DataFrame([[5,4],[6,3],[7,2]],columns=['B','C'])
有没有一种方法可以执行a[1,'a','B']=B[2],从而得到结果

   0   B   C
0  1 NaN NaN
1  2   7   2
2  3 NaN NaN
更新:我对问题做了一点修改,因为答案表明a和b的索引相同,而事实并非如此。

一种可能性:

import pandas as pd

a = pd.DataFrame([1, 2, 3])
b = pd.DataFrame([[5, 4], [6, 3], [7, 2]], columns=['B', 'C'])

a.loc[0, 'B'] = b.loc[0, 'B']
a.loc[0, 'C'] = b.loc[0, 'C']
这表示为
a

   0    B    C
0  1  5.0  4.0
1  2  NaN  NaN
2  3  NaN  NaN
一种可能性:

import pandas as pd

a = pd.DataFrame([1, 2, 3])
b = pd.DataFrame([[5, 4], [6, 3], [7, 2]], columns=['B', 'C'])

a.loc[0, 'B'] = b.loc[0, 'B']
a.loc[0, 'C'] = b.loc[0, 'C']
这表示为
a

   0    B    C
0  1  5.0  4.0
1  2  NaN  NaN
2  3  NaN  NaN

您可以使用
a
上的
join
和所需的
b

In [150]: a.join(b.loc[0:0])
Out[150]:
   0    B    C
0  1  5.0  4.0
1  2  NaN  NaN
2  3  NaN  NaN

您可以使用
a
上的
join
和所需的
b

In [150]: a.join(b.loc[0:0])
Out[150]:
   0    B    C
0  1  5.0  4.0
1  2  NaN  NaN
2  3  NaN  NaN

你觉得pd.concat怎么样

pd.concat([a,b.loc[b.index==0,:]],axis=1)

Out[53]: 
   0    B    C
0  1  5.0  4.0
1  2  NaN  NaN
2  3  NaN  NaN

你觉得pd.concat怎么样

pd.concat([a,b.loc[b.index==0,:]],axis=1)

Out[53]: 
   0    B    C
0  1  5.0  4.0
1  2  NaN  NaN
2  3  NaN  NaN