简体   繁体   中英

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

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'} ...]

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()))
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'}

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.

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