Radeau
Radeau

Reputation: 95

Pandas: wrong values written in a DataFrame using .loc: bug or misunderstanding?

I would like to modify the content of an excel file based on the values inside of a Python dictionary. I am using the .loc function but for some mysterious reason, it works every second time, the other time it writes the column names instead of the values I want to write. Has anyone an input on this:

dict_test={"a":"A","b":1}
df_xxx=pd.DataFrame(columns=["a","b"])
df_xxx.loc["xxx"]={"a":dict_test["a"],"b":dict_test["b"]}
print("DataFrame written to excel:")
print(df_xxx)
df_xxx.to_excel("df_xxx.xlsx") 

#####
print("######")
df_xxx=pd.read_excel("df_xxx.xlsx",index_col=0)
print("DataFrame read from excel:")
print(df_xxx)
df_xxx.loc["xxx"]={"a":dict_test["a"],"b":dict_test["b"]}
print("DataFrame after modification - > written to excel:")
print(df_xxx)
df_xxx.to_excel("df_xxx.xlsx")

#####
print("######")
df_xxx=pd.read_excel("df_xxx.xlsx",index_col=0)
print("DataFrame read from excel:")
print(df_xxx)
df_xxx.loc["xxx"]={"a":dict_test["a"],"b":dict_test["b"]}
print("DataFrame after modification:")
print(df_xxx)

output:

DataFrame written to excel:
     a  b
xxx  A  1
######
DataFrame read from excel:
     a  b
xxx  A  1
DataFrame after modification - > written to excel:
     a  b
xxx  a  b      => why is it written a and b and not A and 1?????
######
DataFrame read from excel:
     a  b
xxx  a  b
DataFrame after modification:
     a  b
xxx  A  1      => why are this time the values A and 1?????

Upvotes: 0

Views: 133

Answers (1)

Limtorak
Limtorak

Reputation: 81

Just ran your code into my Jupyter. Does work ok:

DataFrame written to excel:
     a  b
xxx  A  1
######
DataFrame read from excel:
     a  b
xxx  A  1
DataFrame after modification - > written to excel:
     a  b
xxx  A  1
######
DataFrame read from excel:
     a  b
xxx  A  1
DataFrame after modification:
     a  b
xxx  A  1

Have you tried to do:

print(df_xxx.loc["xxx"])

after the first modification ?

Upvotes: 1

Related Questions