import matplotlib.pyplot as plt
import numpy as np
from sympy import Symbol
from sympy.plotting import plot
x = Symbol('x')
X = np.linspace(-3,3,100)
y = np.cos(X)
def add_plot(p, ax):
backend = p.backend(p)
backend.ax = ax
backend._process_series(backend.parent._series, ax, backend.parent)
backend.ax.spines['right'].set_color('none')
backend.ax.spines['bottom'].set_position('zero')
backend.ax.spines['top'].set_color('none')
plt.close(backend.fig)
p = plot(x**2, (x, 0, 3), show=False)
fig, ax = plt.subplots(1,2, figsize=(18,9))
ax[0].plot(X,y)
add_plot(p, ax[1]);
print(repr(list_of_names[0]))
и на свою строку, приведи их к одному виду, что бы list_of_names[0] == 'Абакус Прайм, СЭ'
возвращал True. И будет работать. df = pd.read_excel('Твой Файл')
df.groupby('Телефон A')['Сумма'].sum()
def write(df, xl_writer, startrow = 0,**kwargs):
df.drop(df.index).to_excel(xl_writer, startrow = startrow,**kwargs)
df.to_excel(xl_writer, startrow = startrow + 1,header = False,**kwargs)
writer = pd.ExcelWriter("test_only_removed_empty_row.xlsx",engine='xlsxwriter')
write(df, writer, sheet_name = 'Лист1')
writer.close()
def write(df, xl_writer, startrow = 0,startcol=0,**kwargs):
df.drop(df.index).to_excel(xl_writer, startrow = startrow,startcol=startcol,**kwargs)
df.droplevel(0,axis=1).to_excel(xl_writer, startrow = startrow + 2, startcol=startcol+1,header = False,index=False,**kwargs)
writer = pd.ExcelWriter("bad_practice.xlsx",engine='xlsxwriter')
write(df, writer, sheet_name = 'Лист1')
writer.close()
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-3,3,100)
fig, ax = plt.subplots(2,1, figsize=(12,6))
ax[0].plot(X, np.sin(X))
ax[0].set_title('sin(x)')
ax[1].plot(X,np.cos(X))
ax[1].set_title('cos(x)')
plt.show();
import pandas as pd
df = pd.DataFrame({
'Stock A':100 * np.cumprod(1 + np.random.normal(0.01,0.05,30)),
'Stock B':100 * np.cumprod(1 + np.random.normal(-0.01,0.05,30))
}, index = pd.date_range('2023-01-01',freq='1D',periods=30))
df.plot();
import numpy as np
import matplotlib.pyplot as plt
class plotCreator:
def __init__(self, x, y,**kwargs):
self.x = x
self.y = y
self.axes_kwargs = kwargs
def plot(self, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
ax.plot(self.x, self.y, **kwargs)
ax.set(**self.axes_kwargs)
return ax
X = np.linspace(-2*np.pi,2*np.pi,100)
y1 = np.cos(X)
y2 = np.sin(X)
img1 = plotCreator(X, y1,xlabel='X',title='cos(X)',ylabel='cos(X)')
img1.plot().figure.savefig('cos.png');
plt.cla()
img2 = plotCreator(X, y2,xlabel='X',title='sin(X)',ylabel='sin(X)')
img2.plot().figure.savefig('sin.png');
from typing import List
def GetAllWorker(db_name: str) -> List[WorkerInformation]:
import pandas as pd
import numpy as np
data = [{ "customer_id": "5f9d7b0a100400c6f00ad1cb",
"customer_pet": "cat",
"customer_cat_color": "gold",
"customer_cat_name": "",
"timestamp": "2023-05-15 12:22:22.111241 UTC",
"list_cart": [
"cart_1",
"cart_2",
"cart_3" ]},
{"customer_id": "5f9d7b0a100400c6f00ad1cb",
"customer_pet": "cat",
"customer_cat_color": "gold",
"customer_cat_name": "",
"timestamp": "2023-05-15 13:33:33.111241 UTC",
"list_cart": [
"cart_3",
"cart_7",
"cart_1" ]}
]
df = pd.DataFrame(data)
print(df['list_cart'].explode().value_counts())
import pandas as pd
import numpy as np
pd.DataFrame(np.where(dataframe_1 != dataframe_2, 'Ваше значение',dataframe_1), columns = dataframe_1.columns)
import pandas as pd
import numpy as np
pd.DataFrame(np.where(dataframe_1 != dataframe_2, dataframe_2,dataframe_1), columns = dataframe_1.columns)
comtraders2 = df_segment
вот это строчку нужно заменить на comtraders2 = df_segment.copy()
И тогда будет работать, как вы ожидаете.df = pd.DataFrame({
'A':[1,2,3],
'B':[4,5,6]
})
subset = df['A']
subset[0] = 100
print(df)
df = pd.DataFrame({
'A':[1,2,3],
'B':[4,5,6]
})
subset = df['A'].copy()
subset[0] = 100
print(df)
import pandas as pd
import numpy as np
songs = {
'ANNA ASTI': ['Девочка танцуй','Грустный дэнс','Гармония'],
'Три дня дождя': ['Демоны','Где ты','Перезаряжай'],
'MACAN': ['Кино','Пополам','Бенз'],
}
NUMBER_OF_DAYS = 3
LENGTH_OF_FINAL_FRAME = sum(len(value) for value in (songs.values())) * NUMBER_OF_DAYS
dates = pd.date_range('2023-01-01', periods=NUMBER_OF_DAYS, freq='1D')
artists = []
for key, value in songs.items():
artists += [key] * len(value)
dates_and_artists = []
for date in dates:
for artist in artists:
dates_and_artists.append((date,artist))
songs_arr = np.array(list(songs.values()) * NUMBER_OF_DAYS).reshape(-1,1)
data = np.concatenate([np.array(dates_and_artists),
songs_arr,
np.random.randint(3000,1_000_000,LENGTH_OF_FINAL_FRAME).reshape(-1,1)], axis=1)
df = pd.DataFrame(data=data, columns=['Date','Artist','Track','Start'])
df
from itertools import chain
import pandas as pd
import numpy as np
songs = {
'ANNA ASTI': ['Девочка танцуй','Грустный дэнс','Гармония'],
'Три дня дождя': ['Демоны','Где ты','Перезаряжай'],
'MACAN': ['Кино','Пополам','Бенз'],
}
NUMBER_OF_DAYS = 3
NUMBER_OF_SONGS_PER_DAY = sum(len(value) for value in (songs.values()))
STARTING_DATE = '2023-01-01'
dates = pd.date_range(STARTING_DATE, periods=NUMBER_OF_DAYS, freq='1D')
artists = list(chain(*[[key] * len(value) for key, value in songs.items()]))
songs_per_day = list(chain(*songs.values()))
index = pd.MultiIndex.from_product([dates,artists],names=['Date','Artist'])
df = pd.DataFrame({
'Songs':songs_per_day * NUMBER_OF_DAYS,
'Start':np.random.randint(3000,1000000,NUMBER_OF_DAYS * NUMBER_OF_SONGS_PER_DAY),
}, index=index).reset_index()
df
np.set_printoptions(suppress=True)
np.set_printoptions(suppress=True, formatter={'float_kind':'{:0.10f}'.format})
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0'
}
r = requests.get(url,headers=headers)
df = pd.read_csv("https://hands-on.cloud/wp-content/uploads/2022/02/catfish_sales_1986_2001.csv")
train = df.Total[:130]
test = df.Total[130:170]
model = ARIMA(train, order=(1, 0, 0),trend='ct').fit()
fc = model.get_forecast(39, alpha=0.05)
fc_series = pd.Series(fc.predicted_mean, index=test.index)
lower_series = pd.Series(fc.conf_int().iloc[:, 0], index=test.index)
upper_series = pd.Series(fc.conf_int().iloc[:, 1], index=test.index)
plt.figure(figsize=(12,5), dpi=100)
plt.plot(train, label='training')
plt.plot(test, label='actual')
plt.plot(fc_series, label='forecast')
plt.fill_between(lower_series.index, lower_series, upper_series, color='k', alpha=.15)
plt.title('Forecast vs Actuals')
plt.legend(loc='upper left', fontsize=8)
plt.show()