简体   繁体   English

使用不同长度的给定列表使 dataframe 具有不同的列长度

[英]Make dataframe having different column length with the given lists of different length

I have two lists of different length and i want to form a DataFrame having these lists as columns of a DataFrame.我有两个不同长度的列表,我想形成一个 DataFrame,将这些列表作为 DataFrame 的列。 Lets say my lists are L1 =["a","b"] L2 = ["g","h","o","y"] L3 = ["k","u","e"]假设我的列表是L1 =["a","b"] L2 = ["g","h","o","y"] L3 = ["k","u","e"]

i want a dataframe in which looks like我想要一个 dataframe 看起来像

 L1 L2 L3
 a  g  k
 b  h  u
    o  e
    y   

The question is just not limited for only three columns.It is in the range of hundreds这个问题不仅限于三列。它在数百个范围内

Following results, it might be looking for, the idea is to convert the list into Data frame, you could also create a function that take as input, list arguments and not type every list into Data-Frame by hand.根据结果,它可能正在寻找,想法是将列表转换为数据帧,您还可以创建一个 function 作为输入,列出 arguments 而不是手动将每个列表输入数据帧。

Example 1:示例 1:

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)

Example 2 (Function passing list arguments):示例 2(函数传递列表参数):

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))

You can use zip_longest iterator from itertools .您可以使用来自itertoolszip_longest迭代器。 It will pad the shorter sequences with fillvalue which is None by default.它将使用默认为Nonefillvalue填充较短的序列。 You can specify something else like an empty string in the example below.您可以在下面的示例中指定其他内容,例如空字符串。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM