【发布时间】:2020-09-11 23:34:39
【问题描述】:
我有两个不同长度的列表,例如 a=[1,2,3] 和 b=[2,3]
我想从他们那里生成一个pd.DataFrame,方法是在列表的开头填充nan,如下所示:
a b
1 1 nan
2 2 2
3 3 3
我会很感激这样做的一种干净的方式。
【问题讨论】:
标签: pandas list dataframe merge concatenation
我有两个不同长度的列表,例如 a=[1,2,3] 和 b=[2,3]
我想从他们那里生成一个pd.DataFrame,方法是在列表的开头填充nan,如下所示:
a b
1 1 nan
2 2 2
3 3 3
我会很感激这样做的一种干净的方式。
【问题讨论】:
标签: pandas list dataframe merge concatenation
使用itertools.zip_longest 和reversed 方法:
from itertools import zip_longest
a=[1,2,3]
b=[2,3]
L = [a, b]
iterables = (reversed(it) for it in L)
out = list(reversed(list(zip_longest(*iterables, fillvalue=np.nan))))
df = pd.DataFrame(out, columns=['a','b'])
print (df)
a b
0 1 NaN
1 2 2.0
2 3 3.0
替代方案,如果 b 的值较少,例如 a 列表:
df = pd.DataFrame(list(zip(a, ([np.nan]*(len(a)-len(b)))+b)), columns=['a','b'])
print (df)
a b
0 1 NaN
1 2 2.0
2 3 3.0
【讨论】:
b.append(np.nan)#append NaN
b=list(set(b))#Use set to rearrange and then return to list
df=pd.DataFrame(list(zip(a,b)), columns=['a','b'])#dataframe
Alternatively
b.append(np.nan)#append NaN
b=list(dict.fromkeys(b))#Use dict to rearrange and return then to list.This creates dict with the items in the list as keys and values as none but in an ordered manner getting NaN to the top
df=pd.DataFrame(list(zip(a,b)), columns=['a','b'])#dataframe
【讨论】: