gpt4 book ai didi

python - 将列表项添加到 DataFrame 列(如果它存在于某个范围内)

转载 作者:行者123 更新时间:2023-12-05 05:51:39 24 4
gpt4 key购买 nike

如果指定位置存在列表项,我将尝试将列表项添加到 DataFrame 中的指定列。

list1 = ['a', 'b', 'c', 'd', 'e']

df = pd.DataFrame(columns = ['Letter', 'Headline 1', 'Headline 2', 'Headline 3', 'Headline 4', 'Headline 5', 'Headline 6'])
data = {'Letter':['one', 'two', 'three', 'four', 'five']}
df = pd.DataFrame(data)

我正在尝试使用一系列 if 语句来做到这一点。如果指定位置有列表项,它会起作用。我确信这不是实现我正在寻找的目标的理想方式。如果列表项之一超出范围,它也不起作用。理想情况下,如果列表项不存在,我想插入一个空字符串。

if list1[0]:
df['Headline1'] = list1[0]

if list1[1]:
df['Headline2'] = list1[1]

if list1[2]:
df['Headline3'] = list1[2]

if list1[3]:
df['Headline4'] = list1[3]

if list1[4]:
df['Headline5'] = list1[4]

if list1[5]:
df['Headline6'] = list1[5]

期望的输出:

  Letter Headline1 Headline2 Headline3 Headline4 Headline5 Headline6
0 one a b c d e
1 two a b c d e
2 three a b c d e
3 four a b c d e
4 five a b c d e

最佳答案

使用DataFrame.assign使用 zip 创建的字典:

L = [f'Headline {x+1}' for x in range(list1)]
d = dict(zip(L, list1))
df = pd.DataFrame(data).assign(**d)
print (df)
Letter Headline 1 Headline 2 Headline 3 Headline 4 Headline 5
0 one a b c d e
1 two a b c d e
2 three a b c d e
3 four a b c d e
4 five a b c d e

L = ['Headline 1', 'Headline 2', 'Headline 3', 'Headline 4', 'Headline 5', 'Headline 6']
d = dict(zip(L, list1))
df = pd.DataFrame(data).assign(**d)
print (df)
Letter Headline 1 Headline 2 Headline 3 Headline 4 Headline 5
0 one a b c d e
1 two a b c d e
2 three a b c d e
3 four a b c d e
4 five a b c d e

关于python - 将列表项添加到 DataFrame 列(如果它存在于某个范围内),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70344687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com