添加列不同长度的 pandas [英] add columns different length pandas
本文介绍了添加列不同长度的 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在熊猫中添加列时遇到问题. 我有DataFrame,尺寸为nxk.在此过程中,我将需要添加维数为mx1的列,其中m = [1,n],但我不知道m.
I have a problem with adding columns in pandas. I have DataFrame, dimensional is nxk. And in process I wiil need add columns with dimensional mx1, where m = [1,n], but I don't know m.
当我尝试这样做时:
df['Name column'] = data
# type(data) = list
结果:
AssertionError: Length of values does not match length of index
我可以添加不同长度的列吗?
Can I add columns with different length?
推荐答案
使用concat并传递axis=1
和ignore_index=True
:
Use concat and pass axis=1
and ignore_index=True
:
In [38]:
import numpy as np
df = pd.DataFrame({'a':np.arange(5)})
df1 = pd.DataFrame({'b':np.arange(4)})
print(df1)
df
b
0 0
1 1
2 2
3 3
Out[38]:
a
0 0
1 1
2 2
3 3
4 4
In [39]:
pd.concat([df,df1], ignore_index=True, axis=1)
Out[39]:
0 1
0 0 0
1 1 1
2 2 2
3 3 3
4 4 NaN
这篇关于添加列不同长度的 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文