我只想在Excel输出中显示过滤的行。下面是示例
df = pd.DataFrame({'Data': [1, 2, 3, 4,
5, 6, 7]})
writer = pd.ExcelWriter('pandasEx.xlsx',
engine ='xlsxwriter')
df.to_excel(writer, sheet_name ='Sheet1')
writer.save()
对于输出,我想隐藏'Data' < 5
处的所有行。这该怎么做?
这等效于应用过滤器并保存excel。
我知道如何去除大熊猫中的公仔或如何过滤大熊猫中的东西。但是我不想在熊猫中删除它们,我只是想在excel中应用过滤器。用例是,用户将在excel中拥有完整的数据,但是某些行将被隐藏,如果用户希望他们可以在excel中取消隐藏它们并查看数据。希望这可以解释用例
谢谢
答案 0 :(得分:1)
df = pd.DataFrame({'Data': [1, 2, 3, 4,
5, 6, 7]})
writer = pd.ExcelWriter('pandasEx.xlsx',
engine ='xlsxwriter')
df.to_excel(writer, sheet_name ='Sheet1')
workbook = writer.book
worksheet1 = writer.sheets['Sheet1']
worksheet1.autofilter('B1:B{}'.format(len(df)))
worksheet1.filter_column('B', 'x < 5')
# Hide the rows that don't match the filter criteria.
row = 1
#for row_data in (df):
for index, row_data in df.iterrows():
region = row_data['Data']
# Check for rows that match the filter.
if region < 5:
# Row matches the filter, no further action required.
pass
else:
# We need to hide rows that don't match the filter.
worksheet1.set_row(row, options={'hidden': True})
# Move on to the next worksheet row.
row += 1
writer.save()
答案 1 :(得分:0)
使用过滤后的数据创建一个数据框,并将其写入excel文件:
import pandas as pd
df = pd.DataFrame({'Data': [1, 2, 3, 4, 5, 6, 7]})
writer = pd.ExcelWriter('pandasEx.xlsx')
df_filtered = df.loc[df.Data >= 5]
df_filtered.to_excel(writer, sheet_name ='Sheet1')
writer.save()
备注:由于我的系统上没有xlswriter
模块,因此必须删除它,但代码也应适用。