How to remove timestamp from datetime column in pandas Style Object
I have a DataFrame with a Date column that has no timestamp:
But once I apply style
to another column in the df, e.g. :
df = df.style.applymap(colorFunction, subset=['column3'])
The DataFrame becomes a Style Object, and the "Date" column gets a timestamp that it didn't have before, as the following:
I tried the following to strip the timestamp from the Date column:
df['Date'].style.apply(lambda x: x.strftime('%Y-%m-%d'))
I got the following error:
TypeError: 'Styler' object is not subscriptable
Is there any way to remove the time stamp from the Style object?
2 answers
-
answered 2022-01-19 16:49
Peter Leimbigler
This is just a stopgap solution, but you can manually specify the usual
%Y-%m-%d
display format for your date column as follows:styled = (df.style .applymap(colorFunction, subset=['column3']) .format({'Date': '{:%Y-%m-%d}'}))
Example
# Example data df = pd.DataFrame({'Date': pd.date_range('2020-01-01', '2020-01-05', freq='d'), 'Value': list(range(-2, 3))}) # Example color function def f(v): return 'color: red;' if v < 0 else None # Unexpected addition of H:M:S to date column df.style.applymap(f, subset='Value')
# Specify desired date format df.style.applymap(f, subset='Value').format({'Date': '{:%Y-%m-%d}'}))
-
answered 2022-01-20 14:02
Samwise
Besides the good answer provided by @Peter Leimbigler, as an alternative solution, converting the Date column to a string before applying the Style prevents the Styler formatter from adding timestamp.
df['Date'] = df['Date'].astype(str)
Using Peter's example:
# Example data df = pd.DataFrame({'Date': pd.date_range('2020-01-01', '2020-01-05', freq='d'), 'Value': list(range(-2, 3))}) # Example color function def f(v): return 'color: red;' if v < 0 else None # Converting the Date column to a string before applying the Style df['Date'] = df['Date'].astype(str) df.style.applymap(f, subset='Value')
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
Any efficient way to compare two dataframes and append new entries in pandas?
I have new files which I want to add them to historical table, before that, I need to check new file with historical table by comparing its two column in particular, one is
state
and another one isdate
column. First, I need to checkmax (state, date)
, then check those entries withmax(state, date)
in historical table; if they are not historical table, then append them, otherwise do nothing. I tried to do this in pandas bygroup-by
on new file and historical table and do comparison, if any new entries from new file that not in historical data, then add them. Now I have issues to append new values to historical table correctly in pandas. Does anyone have quick thoughts?My current attempt:
import pandas as pd src_df=pd.read_csv("https://raw.githubusercontent.com/adamFlyn/test_rl/main/src_df.csv") hist_df=pd.read_csv("https://raw.githubusercontent.com/adamFlyn/test_rl/main/historical_df.csv") picked_rows = src_df.loc[src_df.groupby('state')['yyyy_mm'].idxmax()]
I want to check
picked_rows
inhist_df
where I need to check bystate
andyyyy_mm
columns, so only add entries frompicked_rows
wherestate
hasmax
value or recent dates. I created desired output below. I tried inner join orpandas.concat
but it is not giving me correct out. Does anyone have any ideas on this?Here is my desired output that I want to get:
import pandas as pd desired_output=pd.read_csv("https://raw.githubusercontent.com/adamFlyn/test_rl/main/output_df.csv")
-
How to bring data frame into single column from multiple columns in python
I have data format in these multiple columns. So I want to bring all 4 columns of data into a single column.
YEAR Month pcp1 pcp2 pcp3 pcp4 1984 1 0 0 0 0 1984 2 1.2 0 0 0 1984 3 0 0 0 0 1984 4 0 0 0 0 1984 5 0 0 0 0 1984 6 0 0 0 1.6 1984 7 3 3 9.2 3.2 1984 8 6.2 27.1 5.4 0 1984 9 0 0 0 0 1984 10 0 0 0 0 1984 11 0 0 0 0 1984 12 0 0 0 0
-
Exclude Japanese Stopwords from File
I am trying to remove Japanese stopwords from a text corpus from twitter. Unfortunately the frequently used nltk does not contain Japanese, so I had to figure out a different way.
This is my MWE:
import urllib from urllib.request import urlopen import MeCab import re # slothlib slothlib_path = "http://svn.sourceforge.jp/svnroot/slothlib/CSharp/Version1/SlothLib/NLP/Filter/StopWord/word/Japanese.txt" sloth_file = urllib.request.urlopen(slothlib_path) # stopwordsiso iso_path = "https://raw.githubusercontent.com/stopwords-iso/stopwords-ja/master/stopwords-ja.txt" iso_file = urllib.request.urlopen(iso_path) stopwords = [line.decode("utf-8").strip() for line in iso_file] stopwords = [ss for ss in stopwords if not ss==u''] stopwords = list(set(stopwords)) text = '日本語の自然言語処理は本当にしんどい、と彼は十回言った。' tagger = MeCab.Tagger("-Owakati") tok_text = tagger.parse(text) ws = re.compile(" ") words = [word for word in ws.split(tok_text)] if words[-1] == u"\n": words = words[:-1] ws = [w for w in words if w not in stopwords] print(words) print(ws)
Successfully Completed: It does give out the original tokenized text as well as the one without stopwords
['日本語', 'の', '自然', '言語', '処理', 'は', '本当に', 'しんどい', '、', 'と', '彼', 'は', '十', '回', '言っ', 'た', '。'] ['日本語', '自然', '言語', '処理', '本当に', 'しんどい', '、', '十', '回', '言っ', '。']
There is still 2 issues I am facing though:
a) Is it possible to have 2 stopword lists regarded? namely
iso_file
andsloth_file
? so if the word is either a stopword fromiso_file
orsloth_file
it will be removed? (I tried to use line 14 asstopwords = [line.decode("utf-8").strip() for line in zip('iso_file','sloth_file')]
but received an error as tuple attributes may not be decodedb) The ultimate goal would be to generate a new text file in which all stopwords are removed.
I had created this MWE
### first clean twitter csv import pandas as pd import re import emoji df = pd.read_csv("input.csv") def cleaner(tweet): tweet = re.sub(r"@[^\s]+","",tweet) #Remove @username tweet = re.sub(r"(?:\@|http?\://|https?\://|www)\S+|\\n","", tweet) #Remove http links & \n tweet = " ".join(tweet.split()) tweet = ''.join(c for c in tweet if c not in emoji.UNICODE_EMOJI) #Remove Emojis tweet = tweet.replace("#", "").replace("_", " ") #Remove hashtag sign but keep the text return tweet df['text'] = df['text'].map(lambda x: cleaner(x)) df['text'].to_csv(r'cleaned.txt', header=None, index=None, sep='\t', mode='a') ### remove stopwords import urllib from urllib.request import urlopen import MeCab import re # slothlib slothlib_path = "http://svn.sourceforge.jp/svnroot/slothlib/CSharp/Version1/SlothLib/NLP/Filter/StopWord/word/Japanese.txt" sloth_file = urllib.request.urlopen(slothlib_path) #stopwordsiso iso_path = "https://raw.githubusercontent.com/stopwords-iso/stopwords-ja/master/stopwords-ja.txt" iso_file = urllib.request.urlopen(iso_path) stopwords = [line.decode("utf-8").strip() for line in iso_file] stopwords = [ss for ss in stopwords if not ss==u''] stopwords = list(set(stopwords)) with open("cleaned.txt",encoding='utf8') as f: cleanedlist = f.readlines() cleanedlist = list(set(cleanedlist)) tagger = MeCab.Tagger("-Owakati") tok_text = tagger.parse(cleanedlist) ws = re.compile(" ") words = [word for word in ws.split(tok_text)] if words[-1] == u"\n": words = words[:-1] ws = [w for w in words if w not in stopwords] print(words) print(ws)
While it works for the simple input text in the first MWE, for the MWE I just stated I get the error
in method 'Tagger_parse', argument 2 of type 'char const *' Additional information: Wrong number or type of arguments for overloaded function 'Tagger_parse'. Possible C/C++ prototypes are: MeCab::Tagger::parse(MeCab::Lattice *) const MeCab::Tagger::parse(char const *)
for this line:
tok_text = tagger.parse(cleanedlist)
So I assume I will need to make amendments to thecleanedlist
?I have uploaded the cleaned.txt on github for reproducing the issue: [txt on github][1]
Also: How would I be able to get the tokenized list that excludes stopwords back to a text format like cleaned.txt? Would it be possible to for this purpose create a df of ws? Or might there even be a more simple way?
Sorry for the long request, I tried a lot and tried to make it as easy as possible to understand what I'm driving at :-)
Thank you very much! [1]: https://gist.github.com/yin-ori/1756f6236944e458fdbc4a4aa8f85a2c
-
Heroku buttons styling issue
I made an app locally and pushed it on Heroku. The app is working perfectly on Heroku, however on the Homepage I have 2 buttons ( login and register ). When I run my app locally my buttons have some whitespace in between and they are rounded ( I am using tailwind for this). But on Heroku both buttons are not rounded and there is no whitespace in between them. When I inspect the button on Heroku, I see: class:".... rounded-full", which is what I expected and should have made the button rounded. Anyone has any idea what could cause this and how I can solve this ?
This is how my index.js looks like:
export default function Login() { return( <div> <Loginbuttons/> </div> ) }
and Loginbuttons.js defined as:
import Link from 'next/link' export default function Loginbutton(props){ return ( <div> <div className = 'block'> <button style={{width:"10%", paddingTop:"15px", paddingBottom:"15px"}} className='mt-10 mb-10 bg-blue-500 hover:bg-blue-700 text-wgvhite font-bold py-2 px-4 rounded-full'> <Link href='login' style={{textDecoration: 'none'}}>Login</Link> </button> <button style={{width:"10%", paddingTop:"15px", paddingBottom:"15px"}} className='mt-10 mb-10 ml-10 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full'> <Link href='register' style={{textDecoration: 'none'}}>Register</Link> </button> </div> </div>)}
-
Cannot resolve directory '~bootstrap'
I did npm install in terminal. I downloaded bootstrap. Currently, the codes I wrote over styles.css do not work.
@import "~bootstrap/dist/css/bootstrap.min.css"; @import "~font-awesome/css/font-awesome.min.css";
The errors I got after these codes:
npm audit fix --force
I tried this method but it didn't work
-
Javafx - change Theme (CSS) on active window
I want a Button that allows me to switch between Dark/Light-mode. But I have the problem If I switch, the active windows will not change their Style.
First of the Code snippets to easy recreate the problem. For Maven projects starter class:
package testapp; //This Class is Required in mavenproject to Start the Application public class GUIStarter { public static void main(final String[] args) { try{ TestApp.main(args); }catch (Exception e){ System.out.println("GUIStarter Errror:\n"+e); } } }
The primary Window class:
package testapp; //IMPORT //JAVAFX import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.stage.Stage; //title import javafx.scene.Scene; //IMPORT END public class TestApp extends Application { //stylepaths public static String mainLightModePath = ".\\style_lightmode.css"; public static String mainDarkModePath = ".\\style-Darkmode.css"; public static boolean isItDarkmode = true; public static void toggleMode(){ if(isItDarkmode){ isItDarkmode = false; }else if(!isItDarkmode){ isItDarkmode = true; } } //This is required to get the primary Stage in other Stages (Controllers) private static Stage pStage; public static Stage getPrimaryStage() { return pStage; } private void setPrimaryStage(Stage pStage) { TestApp.pStage = pStage; } public void setPrimaryWindow(Stage primaryStage){ try{ FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Mainframe.fxml")); Parent root = (Parent) fxmlLoader.load(); Scene scene = new Scene(root); primaryStage.setTitle("TestApp"); //scene.setMoveControl(titleBar); primaryStage.setScene(scene); primaryStage.show(); } catch (Exception e){ e.printStackTrace(); } } //Start of Application @Override public void start(Stage primaryStage) { setPrimaryStage(primaryStage); pStage = primaryStage; setPrimaryWindow(primaryStage); } public static void main(String[] args) { launch(args); } }
The maincontroller Class:
package testapp; //IMPORT //JAVAFX import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.stage.Stage; import javafx.scene.Node; import javafx.event.ActionEvent; import javafx.scene.layout.BorderPane; //Countdown import javafx.animation.Timeline; public class Mainframe { public static Timeline time; @FXML public void options(ActionEvent event){ try{ TestApp.toggleMode(); Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow(); Stage changer = TestApp.getPrimaryStage(); stage.close(); changer.hide(); //My idea was to initialize again and load the styles in that way again but does not change anything FXMLLoader loader = new FXMLLoader(getClass().getResource("Mainframe.fxml")); loader.load(); Mainframe ctrl = loader.getController(); ctrl.initialize(); changer.show(); }catch (Exception e) { System.out.println("Error bei der App Klicken von ModeButton. \n error is: "+e); e.printStackTrace(); } } @FXML public BorderPane primaryparent; //get and set for elements @FXML void initialize() { //Check Theme if(TestApp.isItDarkmode){ primaryparent.getStylesheets().clear(); primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainDarkModePath).toString()); }else if(!TestApp.isItDarkmode){ primaryparent.getStylesheets().clear(); primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainLightModePath).toString()); } } }
Mainframe.fxml
:<?xml version="1.0" encoding="UTF-8"?> <?import javafx.geometry.Insets?> <?import javafx.scene.control.Button?> <?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.layout.BorderPane?> <?import javafx.scene.text.Font?> <BorderPane fx:id="primaryparent" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="0.0" minWidth="0.0" prefHeight="224.0" prefWidth="515.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="testapp.Mainframe"> <center> <AnchorPane prefHeight="200.0" prefWidth="200.0" styleClass="rootBackground" BorderPane.alignment="CENTER"> <children> <Button fx:id="setDarkModeButton" layoutX="175.0" layoutY="99.0" mnemonicParsing="false" onAction="#options" styleClass="settingsButton" text="toggle Dark/LightMode"> <font> <Font name="Arial" size="13.0" /> </font> <padding> <Insets bottom="5.0" left="17.0" right="17.0" top="5.0" /> </padding> </Button> </children> </AnchorPane> </center> </BorderPane>
Before I just
overwrote
the "style.css" file and used.stop()
&.show()
. This worked fine. But it can get complicated the morecss-files
you have and after it is packed into a.jar
file it doesn't work anymore.I hope anyone can help me. Because now I have really no Idea...