问题
How can I export a pandas dataframe to slack?
df.to_json() seems like a potential candidate, coupled with the slack incoming webhook, but then parsing the message to display as a nice markdown/html-ized table isn't obvious to me.
Long time listener, first time caller, please go easy on me...
回答1:
There is a .to_html()
method on DataFrames, so that might work. But if you are just looking to cut and paste, Tabulate is a good choice. From the docs:
from tabulate import tabulate
df = pd.DataFrame([["Name","Age"],["Alice",24],["Bob",19]])
print tabulate(df, tablefmt="grid")
Returns
+---+-------+-----+
| 0 | Name | Age |
+---+-------+-----+
| 1 | Alice | 24 |
+---+-------+-----+
| 2 | Bob | 19 |
+---+-------+-----+
Paste that in a code block in Slack and it should show up nicely.
回答2:
Slack doesn't seem to take arbitrary HTML input or format text with escaped newlines which limits to plain text. tabulate
as suggested in another answer works, but if you want something that is self contained this would work. Assuming your data frame is in df
- In python terminal session, jupyter notebook, or print statement run something like
print(repr(df))
. - Copy the output
- Paste in code blocks in slack.
For the data frame I had on hand this is what you would enter in the slack chat box before hitting enter.
```
code sid state triplet
0 SCAN 2057 AL 2057:AL:SCAN
1 SNOW ABY CA ABY:CA:SNOW
2 SNOW 15A21 MT 15A21:MT:SNOW
3 COOP 0010 ID 0010:ID:COOP
4 SNOW 1F01A BC 1F01A:BC:SNOW
```
If you wanted to integrate this as a web service replace the copy/paste stuff with web services/hooks.
来源:https://stackoverflow.com/questions/39792891/what-are-some-ways-to-post-python-pandas-dataframes-to-slack