I am trying to fill an DataFrame with every second word from another element, but that doesn't work:
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 = [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:
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[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:
tab[0]: Banana
tab[1]: Dog
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.