[英]Make dataframe having different column length with the given lists of different length
我有两个不同长度的列表,我想形成一个 DataFrame,将这些列表作为 DataFrame 的列。 假设我的列表是L1 =["a","b"]
L2 = ["g","h","o","y"]
L3 = ["k","u","e"]
我想要一个 dataframe 看起来像
L1 L2 L3
a g k
b h u
o e
y
这个问题不仅限于三列。它在数百个范围内
根据结果,它可能正在寻找,想法是将列表转换为数据帧,您还可以创建一个 function 作为输入,列出 arguments 而不是手动将每个列表输入数据帧。
import pandas as pd
import numpy as np
## your list
L1 =["a","b"]
L2 = ["g","h","o","y"]
L3 = ["k","u","e"]
## Convert List into DataFrame
L1 = pd.DataFrame(L1)
L2 = pd.DataFrame(L2)
L3 = pd.DataFrame(L3)
## Concanate the created DataFrames and Fill 'NaN' with or empty spaces
db =pd.concat([L1,L2,L3], ignore_index=True, axis=1).replace(np.nan, '')
## Results
print(db)
import pandas as pd
import numpy as np
## your list
L1 =["a","b"]
L2 = ["g","h","o","y"]
L3 = ["k","u","e"]
## function passing arguments
def wrapper(*args):
return pd.concat([pd.DataFrame(i) for i in args], ignore_index=True, axis=1).replace(np.nan, '')
## Results
print(wrapper(L1,L2,L3))
您可以使用来自itertools
的zip_longest
迭代器。 它将使用默认为None
的fillvalue
填充较短的序列。 您可以在下面的示例中指定其他内容,例如空字符串。
from itertools import zip_longest
df = pd.DataFrame(zip_longest(L1,L2,L3, fillvalue=''),
columns=['L1','L2','L3'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.