Append exact Timestamp to new DataFrame after looping (Can`t Find TimeStamp related to coefficient)
Wanted to do a Linear regression of Pressure versus time. Converted Timestamp into values and saved in the 'z' column. The timestamp is per minute for 3 days. I gave 15-minute intervals and created Time1 and Time2 (something like rolling windows) Problem is that I obtain the model. coef_ but cant extract related Timestamps.
minute_summary['z'] = minute_summary['Timestamp'].apply(lambda x: time.mktime(x.timetuple()))
t_s = minute_summary[['Time1','Time2']].copy()
t_s = t_s.dropna()
ks = pd.DataFrame()
ks1 = pd.DataFrame()
for i in range(len(minute_summary)):
to_work = minute_summary[(minute_summary['Timestamp'] >= t_s.iloc[i][0]) & (minute_summary['Timestamp'] <= t_s.iloc[i][1])]
# ks = ks.append(pd.DataFrame(to_work['Timestamp']))
to_work = to_work[['Timestamp', '(DHP)', 'z']].copy().dropna()
y = np.asarray(to_work['(DHP)'])
x = np.asarray(to_work[['z']])
model = LinearRegression() #create linear regression object
model = LinearRegression().fit(x, y) #train model on train data
r_sq = model.score(x, y)
ks = ks.append(pd.DataFrame(model.coef_)).reset_index(drop=True)
ks1 = ks1.append(pd.DataFrame(minute_summary['Timestamp'])).reset_index(drop=True)
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
-
why is my slice not updating when I append?
I'm trying to append a slice in a struct but it simply won't update. I understand that go is mostly pass by value, but aren't slices already pointers to an underlying array?
I've even tried passing the values through my change function(which uses pointers?) But yet I still get the same result.
package main import "fmt" type BookingInfoNode struct { Car string Date string BookingTime int } type user struct { Username string UserBookings []*BookingInfoNode } var mapUsers = make(map[string]user) func init() { mapUsers["john"] = user{"john", []*BookingInfoNode{}} } func change(a []*BookingInfoNode, booking *BookingInfoNode) []*BookingInfoNode { a = append(a, booking) return a } func main() { newBooking := &BookingInfoNode{"mazda", "03/06/2022", 0600} myUser := mapUsers["john"] myUser.UserBookings = change(myUser.UserBookings, newBooking) fmt.Println(myUser.UserBookings) fmt.Println(mapUsers["john"].UserBookings) }
With my two printlns I'm expecting:
[memory address] [memory address]
But I'm getting:
[memory address] []
-
How to add rows based on values in another column
I would like to append rows based on value in another column -
fruit value 'grape' 1 'apple' 2 'peach' 3
Wanted output - I would like to append rows by *n when the value is larger than 1.
'apple'
row will be populated twice, and'grape'
row will be populated three timesfruit value 'grape' 1 'apple' 2 'apple' 2 'peach' 3 'peach' 3 'peach' 3
-
Append a column to an existing data frame, based on a conditional statement from a shorter data frame in R
A seemgly easy question, for which I can't find a solution. I even tried work arounds with for and if loops.
I have a long data frame and a short data frame. I want to add information from the short data frame to the long data frame at the correct positions. In other words: I want to append a column to an existing data frame, based on a conditional statement from a shorter data frame. So I want to merge data frames based on a conditional statement with characters.
data.frame.short <- data.frame(names=c("John", "Mary", "Achmed", "Ali", "Lin"), age=c(23, 34, 44, 42, 52)) data.frame.long <- data.frame(names=c("Mary", "Jamilla", "Achmed", "John", "Ali", "Lin", "Michael", "Abdul"))
The result should be the added column age of data.frame.short to the data.frame.long, at the correct positions. Everything else should be filled with NA. Thus, the results should be:
data.frame.long.appended <- data.frame(names=c("Mary", "Jamilla", "Achmed", "John", "Ali", "Lin", "Michael", "Abdul"), age=c(34, NA, 44, 23, 42, 52, NA, NA))
-
Linear regression with gradient descent won't converge
I've written linear regression from scratch. The fit function calculates partial derivatives at each epoch for slope (m) and bias (b) and updates these variables using their partial derivatives.
My loss decreases, but it gets stuck at a curious place.
The code:
class LinearRegression: def __init__(self): self.m = 3 self.b = 2 def fit(self, x, y, epochs, lr): for epoch in range(epochs): pred = (self.m * x) + self.b cur_loss = np.sum((y - pred)**2) if epoch % 1000 == 0: print(cur_loss) pd_wrt_m = (-2/x.size) * np.sum((y - pred) * x) pd_wrt_b = (-2/x.size) * np.sum(y - pred) self.m -= (lr * pd_wrt_m) self.b -= (lr * pd_wrt_b) def predict(self, x): return (self.m * x) + self.b lr_model = LinearRegression() lr_model.fit(x, y, 10000, 0.01) Y_pred = lr_model.predict(x) plt.scatter(x, y) plt.plot([min(x), max(y)], [min(Y_pred), max(Y_pred)], color='red') # regression line plt.show()
And this is the output when the above code is executed.
I've tried smaller and larger learning rates, smaller and larger epoch counts, but it seems to be the case that wherever the initial m and b values start out, they always stop converging at this particular position.
I've reread my code and could not find a mistake. What could I be doing wrong?
-
predict function producing too high y values
hi can anyone tell me why my linear regression line is being displayed like https://imgur.com/gallery/u3L2avz. i reverted back to a previous version of my python script that was working before however I mustve edited something for it to be displayed like this.
the y values being predicted are: https://pastebin.com/HkR2JzvU
the actual y values are: https://pastebin.com/gTW90urJ
This is my code:
data = pd.read_csv('food.csv') x = data['Date'].values x = pd.to_datetime(x, errors="coerce") x = x.values.astype("float64").reshape(-1,1) y = data['TOTAL'].values.reshape(-1,1) reg = LinearRegression() reg.fit(x, y) print(f"The slope is {reg.coef_[0][0]} and the intercept is {reg.intercept_[0]}") predictions = reg.predict(x.reshape(-1, 1)) x= data['Date'].astype('str') plt.scatter(x, y,c='black') plt.plot(x, predictions, c='blue', linewidth=2) plt.show()
- Keyerror while using using shift() function of pandas while removing autocorrelation in multiple linear regression