简体   繁体   English

Pandas - 将 pandas df 写入 excel 中的下一个空行

[英]Pandas - Write a pandas df to the next empty row in excel

I am currently looking for a solution.我目前正在寻找解决方案。 Is there a functionality that will look for the next empty row in excel and then paste a pandas df here.是否有功能会在 excel 中查找下一个空行,然后在此处粘贴 pandas df。 (note the pandas df has the same dimensions as the data in excel). (注意 pandas df 与 excel 中的数据具有相同的维度)。

Thanks谢谢

Data in Excel Excel中的数据

Employee No.员工号码。 Name名称 Country国家
111111111 111111111 John约翰 Spain西班牙
222222222 222222222 Mary玛丽 Italy意大利

Pandas DF I want to write to the excel sheet Pandas DF 我要写到excel表

Employee No.员工号码。 Name名称 Country国家
333333333 333333333 Michael迈克尔 Ireland爱尔兰
444444444 444444444 George乔治 South Africa南非

Final excel worksheet最终 excel 工作表

Employee No.员工号码。 Name名称 Country国家
111111111 111111111 John约翰 Spain西班牙
222222222 222222222 Mary玛丽 Italy意大利
333333333 333333333 Michael迈克尔 Ireland爱尔兰
444444444 444444444 George乔治 South Africa南非

please note I need to write the pandas DF to an excel sheet entitled "Sheet3"请注意,我需要将 pandas DF 写入名为“Sheet3”的 excel 工作表

This is tough without seeing your code.如果没有看到您的代码,这很难。 I think what Rafael M R de Rezende said is correct.我认为 Rafael M R de Rezende 所说的是正确的。

Say your excel file is like:假设您的 excel 文件如下:

df2 = pd.DataFrame([[111, 'John', 'Spain'], [222, 'Mary', 'Italy']],
               columns=['Employee #', 'Names', 'Countries'])

The new df is:新的 df 是:

df = pd.DataFrame([[333, 'Michael', 'Ireland'], [444, 'George', 'S. Africa']],
               columns=['Employee No.', 'Name', 'Country'])

checking the shape print(df.shape) or print(df2.shape) both results in (2,3).检查形状print(df.shape)print(df2.shape)都会导致 (2,3)。

Next: Use concat ...下一步:使用concat ...

df = pd.concat([df2, df])
print(df.shape)

and the shape becomes (4,6) because the columns names are not the same.并且形状变为 (4,6) 因为列名不相同。 If this is what your experiencing just change above like below you can copy the columns names over.如果这就是您的经历,就像下面那样发生了变化,您可以复制列名。

df2.columns = df.columns # copies column names over
df = pd.concat([df2, df])
print(df)

The results is:结果是:

   Employee No.     Name       Country
0       111         John         Spain
1       222         Mary         Italy
0       333      Michael       Ireland
1       444       George  South Africa

When saving, I recommend using df.to_csv(yourfile.csv, index=False) it is easier to work with, it is what I do.保存时,我建议使用df.to_csv(yourfile.csv, index=False)它更容易使用,我就是这样做的。 Referenceconcat and df.to_csv参考concatdf.to_csv

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

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