Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

populate pandas dataframe using csv file

$
0
0

I have two files:

File1: An empty dataframe with only a header. (the data frame I wish to populate)

item A B C D E F G H

File2: A CSV file with space-delimited elements with uneven column numbers

item1 A B D F item2 A B C D Eitem3 A H I item4 C D E F Gitem5 K L

The output I expect is the following:

item |A|B|C|D|E|F|G|H----------------------item1 A B   D   Fitem2 A B C D Eitem3 A             Hitem4     C D E F G

The code is below and partially working:

import pandas as pddf = pd.read_csv('to_map.txt', delim_whitespace=True, header=0)with open('to_search.txt', "r") as f:    for line in f:        elements = line.strip().split(" ")        first_element = elements[0]        row = {}  # Create an empty dictionary for each row        for element in elements:            row[element] = first_element            if element in df.columns:                row[element] = element  # Match found, update to corresponding column            else:                row[element] = pd.NA  # Match not found, assign NA        # Append the row to the DataFrame        df = df._append(row, ignore_index=True)print(df)

The output of the above code is:

item    A    B    C    D    E    F    G    H item1 item2 item3    I item4  \0  NaN    A    B  NaN    D  NaN    F  NaN  NaN   NaN   NaN   NaN  NaN   NaN   1  NaN    A    B    C    D    E  NaN  NaN  NaN   NaN   NaN   NaN  NaN   NaN   2  NaN    A  NaN  NaN  NaN  NaN  NaN  NaN    H   NaN   NaN   NaN  NaN   NaN   3  NaN  NaN  NaN    C    D    E    F    G  NaN   NaN   NaN   NaN  NaN   NaN   4  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN   NaN   NaN   NaN  NaN   NaN     item5    K    L  0   NaN  NaN  NaN  1   NaN  NaN  NaN  2   NaN  NaN  NaN  3   NaN  NaN  NaN  4   NaN  NaN  NaN 

As you can see, the item(1..n), K, L, though not in column header, it still written as separate column and filled with NaNs. Please help !


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>