'dataframe works if I take data from another dataframe but not if add it directly
I am hoping someone can help me understand why a dataframe works one way but not the other. I am relatively new to Python but do have a decent understanding of Pandas. However I can't figure out why I can't add data to the empty dataframe directly first without getting data from another dataframe. I know there are plenty of ways around this. I am just curious as to why.
Thank you for any light you may be able to shed on this.
import pandas as pd
source_df = pd.DataFrame({'iset':['1001']})
print(source_df)
column_names = ['Import Set No','col2']
df = pd.DataFrame(columns = column_names)
df.loc[:,'col2'] = 2
df.loc[:,'Import Set No'] = source_df.loc[:,'iset']
print(df)
Produces:
iset
0 1001
Empty DataFrame
Columns: [Import Set No, col2]
Index: []
And:
import pandas as pd
source_df = pd.DataFrame({'iset':['1001']})
print(source_df)
column_names = ['Import Set No','col2']
df = pd.DataFrame(columns = column_names)
df.loc[:,'Import Set No'] = source_df.loc[:,'iset']
df.loc[:,'col2'] = 2
print(df)
Produces:
iset
0 1001
Index(['Import Set No', 'col2'], dtype='object')
Import Set No col2
0 1001 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
