1
Columns: [TERMID, NAME, TYP, NAMECHANGE, ALIASES, SUCHREGELN, ZUW, SEOTEXT1, SEOTEXT2, SEOKommentar, DBIKommentar]

This is my empty dataframe.

      one  two  three  four
0  1.0  4.0    2.4   6.4
1  2.0  3.0    4.4   4.1
2  3.0  2.0    7.0   1.0
3  4.0  1.0    9.0   5.0

I need to fill these values into my empty dataframe.

So lets say'TERMID' takes the value from 'one', 'TYP' the value of 'two', 'ZUW' the value from 'three' and last but not least 'SEOKommentar' takes the value from 'four'

The empty dataframe needs to get filled row by row, and the ones which are not filled should say NaN.

How can I do this in an accurate way?

2

1 Answer 1

1

IIUC, you can rename the second dataframe and then reindex the columns to the original empty dataframe columns:

Creating the empty data frame:

s = 'TERMID,NAME,TYP,NAMECHANGE,ALIASES,SUCHREGELN,ZUW,SEOTEXT1,SEOTEXT2,SEOKommentar,DBIKommentar'
df = pd.DataFrame(columns=s.split(','))

Empty DataFrame
Columns: [TERMID, NAME, TYP, NAMECHANGE, ALIASES, SUCHREGELN, ZUW, SEOTEXT1, SEOTEXT2, SEOKommentar, DBIKommentar]
Index: []

Solution (df1 is the second dataframe in your example):

d = {'one': 'TERMID', 'two': 'TYP', 'three': 'ZUW', 'four': 'SEOKommentar'}
df = df1.rename(columns=d).reindex(columns=df.columns)

   TERMID  NAME  TYP  NAMECHANGE  ALIASES  SUCHREGELN  ZUW  SEOTEXT1  \
0     1.0   NaN  4.0         NaN      NaN         NaN  2.4       NaN   
1     2.0   NaN  3.0         NaN      NaN         NaN  4.4       NaN   
2     3.0   NaN  2.0         NaN      NaN         NaN  7.0       NaN   
3     4.0   NaN  1.0         NaN      NaN         NaN  9.0       NaN   

   SEOTEXT2  SEOKommentar  DBIKommentar  
0       NaN           6.4           NaN  
1       NaN           4.1           NaN  
2       NaN           1.0           NaN  
3       NaN           5.0           NaN  
Sign up to request clarification or add additional context in comments.

4 Comments

This raises a ValueError in my code. Saying I cannot reindex from a duplicate axis
@yannickhau do you have duplicate column names? works fine for the example you have provided in the question
yeah there is one named the same.. should I rename this one first probably?
@yannickhau if possible yes, you shouldnt be having 2 same column names ideally

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.