我是Python编程的新手,我正在尝试制作一个CLI,允许用户使用Pandas和Click使用一些预定义的命令过滤csv数据。我目前为用户提供了列出原始数据和按颜色过滤数据的选项。我的list((和color((函数似乎按照我希望的方式工作
我想添加一个save((函数,允许用户在过滤后将数据导出到一个新的CSV文件中,但我不知道如何将过滤后的数据传递给save((功能。
这是我目前拥有的代码。
#!/usr/bin/env python
import click #imports click for CLI commands
import pandas as pd #import for pandas
df = pd.read_csv('dogs.csv') #reads the original data set.
@click.group() #creates a group
@click.help_option('--help', help='displays the list of available commands') #adds help option
def cli():
pass
##this shows the original list of cats
@click.command()
def list():
"""Simple command that lists all original dogs."""
click.echo(f"{df}")
### this lists the filtered list of colored cats
@click.command()
@click.option("--color", prompt="Enter the desired color", help="The color of the dogs")
def color(color):
"""Simple command that filters dogs based on COLOR."""
color = color.lower()
new_df = df[df['Color'].str.contains(color)]
click.echo(f"{new_df}")
### i want this to save the changes to a new csv file
@click.command()
@click.option("--save", help="Saves the file")
def save(save):
"""Simple command that saves the filtered list of dogs."""
# i am lost here
save = new_df
click.echo(f"{save}")
### add all commands to group
cli.add_command(list)
cli.add_command(color)
cli.add_command(save)
if __name__ == "__main__":
cli()
我尝试将new_df设置为全局变量,但没有成功。我还尝试返回new_df,,但也不起作用。
我正试图将color((函数的过滤结果传递到save((,以便将过滤后的更改导出为csv。这是我在Python中可以做的事情吗?
如果我理解正确,您希望将color
命令的结果保存到一个文件中(或者如果没有任何文件提供,只需将其打印到屏幕上(:
import click # imports click for CLI commands
import pandas as pd # import for pandas
# sample dataframe:
df = pd.DataFrame({"Name": ["Bob", "Rex"], "Color": ["White", "Brown"]})
@click.group() # creates a group
@click.help_option(
"--help", help="displays the list of available commands"
) # adds help option
def cli():
pass
##this shows the original list of cats
@click.command()
def list():
"""Simple command that lists all original dogs."""
click.echo(f"{df}")
### this lists the filtered list of colored cats
@click.command()
@click.option(
"--color", prompt="Enter the desired color", help="The color of the dogs"
)
@click.option("--save", default=None, type=click.Path())
def color(color, save):
"""Simple command that filters dogs based on COLOR."""
new_df = df[df.Color.str.lower() == color.lower()]
if not save:
click.echo(f"{new_df}")
else:
new_df.to_csv(save, index=False)
click.echo(f"Dataframe saved to {save}")
### add all commands to group
cli.add_command(list)
cli.add_command(color)
if __name__ == "__main__":
cli()
这将为color
命令添加选项:
$ python3 example.py color --help
Usage: example.py color [OPTIONS]
Simple command that filters dogs based on COLOR.
Options:
--color TEXT The color of the dogs
--save PATH
--help Show this message and exit.
然后你可以用调用它
$ python3 example.py color --save data.csv
Enter the desired color: white
Dataframe saved to data.csv
保存data.csv
:
Name,Color
Bob,White