简体   繁体   中英

python pandas - Append columns to an empty dataframe with a for loop

I have 2 dataframes, c_r and x . I am trying to append an empty dataframe, with this code:

new_df = pd.DataFrame()

for i in c_r:
    for j in x:
        if c_r[i].dtype != object and x[j].dtype != object:
            if i == j:
                col_c = c_r[i]
                col_j = x[j]
                new_df[i+'-Diff'] = col_c - col_j
        
        else:
            break

But I keep getting back an empty data frame. Can anyone suggest what I am doing wrong? Thanks

Your code works just fine, but might be unecessary. But if you want to use it. I created the dfs as c_r in

EOL - CL Per $;Access - CL Per $;Total Impact - CL Per $
-0.02;-0.39;-0.01
-0.02;-0.39;-0.02
-0.02;-0.39;-0.01
-0.02;-0.39;-0.02

and x in

EOL - CL Per $;Access - CL Per $;Total Impact - CL Per $
-0.02;-0.39;0.05
-0.02;-0.39;0.03
-0.02;-0.39;0.06
-0.02;-0.39;0.04

And then

c_r = pd.read_csv(r"C:/users/k_sego/c_r.csv", sep=";")
x = pd.read_csv(r"C:/users/k_sego/x.csv", sep=";")

Your code

new_df = pd.DataFrame()

for i in c_r:
    for j in x:
        if c_r[i].dtype != object and x[j].dtype != object:
            if i == j:
                col_c = c_r[i]
                col_j = x[j]
                new_df[i+'-Diff'] = col_c - col_j
        
        else:
            break

works just ok and gives

   EOL - CL Per $-Diff  Access - CL Per $-Diff  Total Impact - CL Per $-Diff
0                  0.0                     0.0                         -0.06
1                  0.0                     0.0                         -0.05
2                  0.0                     0.0                         -0.07
3                  0.0                     0.0                         -0.06

So,if it doesn'twork for you it must have to do with the files you have.

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