gpt4 book ai didi

python - 使用 for 循环在数据框中添加值

转载 作者:太空宇宙 更新时间:2023-11-04 11:17:00 26 4
gpt4 key购买 nike

我是 StackOverflow 的新手

这是我第二次问类似的问题,因为第一个问题不清楚而且是重复的。顺便说一句,我是新手,正在尝试学习网络抓取。

这是我到目前为止所做的:

我有一个字符串列表,其中第一个索引是列名,下一个索引是它的值。同样,第三个索引是列名,但具有不同的名称,第四个索引是值。

我想将所有这些列表放入列名为“i”且值为“i_next”的数据框中

text=my_detail[0].split('\n')
#for example text=['a','2','b','3',c,'4'] <is a list not dataframe>
#some of the string in text is not require
#example the text can be ['a','2','f','b','3','c','4']

df = pd.DataFrame(columns=['a','b','c'])

for i,nexti in zip(text,text[1:]):

if i in df.columns:
#store df at column name i having value nexti
'''
The expected answer is
a b c
2 3 4
'''

如果这个问题再次出现任何问题或重复,您可以发表评论,我会删除它。

感谢您的考虑,

最佳答案

使用DataFrame构造函数,通过索引获取values的值:

df = pd.DataFrame([text[1::2]], columns=text[::2])
print (df)
a b c
0 2 3 4

编辑:

循环解决方案 - 想法是创建字典列表并将其传递给 DataFrame 构造函数:

L= [['a\n2','b\n3','c\n4'], ['a\n20','b\n30','c\n40']]

final = []
for x in L:
inner = {}
for y in x:
text = y.split('\n')
for a, b in zip(text[::2],text[1::2]):
inner[a] = b
final.append(inner)

print (final)
[{'a': '2', 'b': '3', 'c': '4'}, {'a': '20', 'b': '30', 'c': '40'}]

df = pd.DataFrame(final)
print (df)

a b c
0 2 3 4
1 20 30 40

关于python - 使用 for 循环在数据框中添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56783898/

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