繁体   English   中英

python pandas - Append 列到一个空的 dataframe

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

我有 2 个数据框, c_rx 我正在尝试append一个空的 dataframe,使用以下代码:

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

但我不断地取回一个空的数据框。 谁能建议我做错了什么? 谢谢

您的代码工作得很好,但可能是不必要的。 但是如果你想使用它。 我将 dfs 创建为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

x

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

接着

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=";")

你的代码

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

工作正常并给出

   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

因此,如果它对您不起作用,则它必须与您拥有的文件有关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM