简体   繁体   English

用来自 For-Loop 的数据填充 Dataframe

[英]Filling Dataframe with data from For-Loop

I am trying to fill an DataFrame with every second word from another element, but that doesn't work:我正在尝试用来自另一个元素的每隔一个单词填充 DataFrame,但这不起作用:

import pandas as pd

   
output[0] = "Word 1"
output[2] = "Word 2"
output[4] = "Word 3"

tab = pd.DataFrame(index=5, columns=1)
tab = tab.fillna(0)
f=0
for i in range(1,len(output),2):
    tab[f]=output[i]
    f=f+1
    print(output[i])

It is not very clear what you are trying to achieve, please review this and edit your question目前尚不清楚您要达到的目标,请查看内容并编辑您的问题

But going out on a limb here, suppose you have a list output :但是在这里,假设您有一个列表output

output = [f'Word {n}' for n in range(10)]
print(output)

that looks like this:看起来像这样:

['Word 0', 'Word 1', 'Word 2', 'Word 3', 'Word 4', 'Word 5', 'Word 6', 'Word 7', 'Word 8', 'Word 9']

then you can create a dataframe from every second element of this list using the slicing operator for lists:然后您可以使用列表的切片运算符从此列表的每隔一个元素创建 dataframe :

df = pd.DataFrame(output[::2])
df

we get我们得到

    0
0   Word 0
1   Word 2
2   Word 4
3   Word 6
4   Word 8
data = {'Words': output}
df = pd.DataFrame.from_dict(data)
df = df.iloc[::2]

Thank you for your answer.谢谢您的回答。 And it´s true, my question wasn't really precise.确实,我的问题并不准确。

I split a string and got an element with different words.我拆分了一个字符串并得到了一个包含不同单词的元素。 But just every second row contains a word that i need, the other rows contains just useless data.但是每隔一行包含一个我需要的单词,其他行只包含无用的数据。

So the output file looks like this:所以 output 文件看起来像这样:

output[0]: lkjlajsflkjaf
output[1]: Banana
output[2]: lksjdflkjsdfljk
output[3]: Dog

I want to filter out every second word to get a dataframe with just the words I need, in this case:我想过滤掉每个第二个单词以获得 dataframe 只包含我需要的单词,在这种情况下:

tab[0]: Banana
tab[1]: Dog 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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