Home > database >  How to get rid of Series heading (column heading) using Pandas Library in Python
How to get rid of Series heading (column heading) using Pandas Library in Python

Time:11-11

Using pandas Library, I made dictionaries that are nested in a list from file “german_words.csv”. (for Info: “german_words.csv” is file with German words and corresponding English translated words)

german_words.csv (It's just sample, current file contains thousands of words):

Deutsch,English
Gedanken,thought
Stadt,city
Baum,tree
überqueren,cross
Bauernhof,farm
schwer,hard
Beginn,start
Macht,might
Geschichte,story
Säge,saw
weit,far
Meer,sea

Here's the code of that:

import pandas
import random

word_data = pandas.read_csv("./data/german_words.csv")
word_data_list = word_data.to_dict(orient="records")
print(random.choice(word_data_list))


And then printing random dictionary from that list.

list looks like this:

[{'Deutsch': 'Gedanken', 'English': 'thought'}, {'Deutsch': 'Stadt', 'English': 'city'}, {'Deutsch': 'Baum', 'English': 'tree'}, ....]

Here's the sample output:

{'Deutsch': 'Küste', 'English': 'coast'}

But the problem is, I don't want the column heading in the dictionaries.

I want these dictionaries in list as follows:

[{'Gedanken': 'thought'}, {'Stadt': 'city'}, {'Baum': 'tree'} ...]

CodePudding user response:

Create Series by column Deutsch like index, select column English and then convert to dictionaries:

print (word_data.set_index('Deutsch')['English'].to_dict())

Or if only 2 columns DataFrame is possible use:

print (dict(word_data.to_numpy()))

CodePudding user response:

import pandas as pd

word_data = pd.DataFrame(
    data={
        "Deutsch": ["Gedanken", "Stadt", "Baum"],
        "English": ["thought", "city", "tree"],
    }
)

print({d["Deutsch"]: d["English"] for d in word_data.to_dict(orient="records")})
# {'Gedanken': 'thought', 'Stadt': 'city', 'Baum': 'tree'}
  • Related