我有一个数据框,如下:
ID Date Volume Sales
1 2020-02 10 4
1 2020-03 8 6
2 2020-02 6 8
2 2020-03 4 10
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法可以使用重采样将其转换为每周数据?将销量和销量列除以该月的周数?
我已经开始了我的流程,代码如下:
import pandas as pd
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index('date')
grouped = df.groupby('ID').resmaple('W').ffill().reset_index()
print(grouped)
Run Code Online (Sandbox Code Playgroud)
执行此步骤后,我收到错误消息:无法插入 ID,已存在
还有一个代码可用于查找一个月中的周数,以便将销量和销售额列除以该月中的周数。
预期输出是:
ID Volume Sales Weeks
0 1 2.5 1.0 2020-02-02
0 1 2.5 1.0 2020-02-09
0 1 2.5 1.0 2020-02-16
0 1 2.5 1.0 2020-02-23
1 1 1.6 1.2 2020-03-01
1 1 1.6 1.2 2020-03-08
1 1 1.6 1.2 2020-03-15 …Run Code Online (Sandbox Code Playgroud) 我正在努力完成一项明显简单的任务,希望在这里找到一些帮助!
我有类似以下数据框的内容。
d = [
['2021-06-01 08:00:00',"A"],
['2021-06-01 09:00:00',"A"],
['2021-06-01 12:00:00',"B"],
['2021-06-01 13:00:00',"B"],
['2021-06-01 18:00:00',"B"],
['2021-06-01 19:00:00',"B"],
['2021-06-01 22:00:00',"C"],
['2021-06-01 23:00:00',"C"]]
df=pd.DataFrame(data=d, columns=("timestamp", "session"))
Run Code Online (Sandbox Code Playgroud)
我想确定会话中大于阈值(例如 1 小时)的时间间隔。
为此目的,不应考虑会话之间的时间间隙,我使用.diff()方法来定位间隙。
df["timestamp"]= pd.to_datetime(df["timestamp"])
df["gap"]=df["timestamp"].diff().dt.seconds > 3600
Run Code Online (Sandbox Code Playgroud)
主要任务是找到会话中的间隙,并通过使用例如重命名部分/会话来将会话切成碎片uuid.uuid4()。
在该示例中,它将导致第 5/6 行出现新的会话名称。
我的方法是对独特会话进行迭代,但是当我在“间隙”列中找到True时,我无法重命名这些部分。
我想留在“熊猫世界”,因为这是一项大数据任务。
让我有一个数据框df
Name Age Job
Rick 24 Worker
Max 20 Worker
Sam 48 Driver
Expected output:
Name
Job
Run Code Online (Sandbox Code Playgroud)
现在,我想打印出那些具有对象类型数据的列(名称)。
这是我的尝试:
for column in df:
if df.dtypes(column) == 'object':
print(column)
Run Code Online (Sandbox Code Playgroud)
但我收到一个错误: “ if df.dtypes(column) == 'object': TypeError: 'Series' object is not callable ”
假设我有一个 DataFrame,如下所示:
| 姓名 | 第一小时内的工作时间 | 第一小时浪费的时间 | 工作时间为第 2 小时 | 第 2 小时浪费时间 |
|---|---|---|---|---|
| 富 | 45 | 15 | 40 | 20 |
| 酒吧 | 35 | 25 | 55 | 5 |
| 巴兹 | 50 | 10 | 45 | 15 |
我希望在第一小时列和第二小时列上使用熔化,使其看起来像这样:
| 姓名 | 小时数 | 工作时间以 hr 为单位 | 时间浪费在hr上 |
|---|---|---|---|
| 富 | 1 | 45 | 15 |
| 富 | 2 | 40 | 20 |
| 酒吧 | 1 | 35 | 25 |
| 酒吧 | 2 | 55 | 5 |
| 巴兹 | 1 | 50 | 10 |
| 巴兹 | 2 | 45 | 15 |
我如何将“第一小时的工作时间”和“第一小时浪费的时间”分组在一起,以便我可以将它们融合到同一行中?
我有一个从 Pandas 延伸出来的问题:条件滚动计数。我想在数据框中创建一个新列,反映满足多个条件的累积行数。
使用以下示例和来自 stackoverflow 25119524 的代码
import pandas as pd
l1 =["1", "1", "1", "2", "2", "2", "2", "2"]
l2 =[1, 2, 2, 2, 2, 2, 2, 3]
l3 =[45, 25, 28, 70, 95, 98, 120, 80]
cowmast = pd.DataFrame(list(zip(l1, l2, l3)))
cowmast.columns =['Cow', 'Lact', 'DIM']
def rolling_count(val):
if val == rolling_count.previous:
rolling_count.count +=1
else:
rolling_count.previous = val
rolling_count.count = 1
return rolling_count.count
rolling_count.count = 0 #static variable
rolling_count.previous = None #static variable
cowmast['xmast'] = cowmast['Cow'].apply(rolling_count) #new …Run Code Online (Sandbox Code Playgroud) 我正在做一个个人项目来练习熊猫和美丽的汤,我抓取了这个信息并将它放在一个熊猫 df 中,如下所示:
0 €8.5M
1 €0
2 €9.5M
3 €2M
4 €21M
...
16534 €1.8M
16535 €1.1M
16536 €550K
16537 €650K
16538 €1.1M
Name: Value, Length: 16539, dtype: object
0 €67K
1 €0
2 €15K
3 €11K
4 €13K
...
16534 €3K
16535 €2K
16536 €2K
16537 €7K
16538 €3K
Name: Wage, Length: 16539, dtype: object
Run Code Online (Sandbox Code Playgroud)
所以为了分析这些信息,我想清理这些数据并将其转换为整数,我能想到的是:
df['Wage'] = df['Wage'].apply(lambda x: re.sub('€','',x))
df['Wage'] = df['Wage'].apply(lambda x: re.sub('K','000',x))
df['Value'] = df['Value'].apply(lambda x: re.sub('€','',x))
df['Value'] = df['Value'].apply(lambda x : re.sub('M','00000',x) if …Run Code Online (Sandbox Code Playgroud) 我正在尝试从以下数据帧()为不同位置创建数据透视表df:
| 地点 | 类别 | 地位 | 价格 |
|---|---|---|---|
| 1 | 家具 | 新的 | 100 美元 |
| 1 | 家具 | 老的 | 50 美元 |
| 2 | 办公用品 | 新的 | 200 美元 |
| 1 | 家具 | 新的 | 100 美元 |
| 1 | 办公用品 | 新的 | 300 美元 |
| 1 | 办公用品 | 老的 | 150 美元 |
首先,我使用代码过滤了数据帧以分离位置 1 和 2:
df1 = df[df['Location'] == 1]
df2 = df[df['Location'] == 2]
Run Code Online (Sandbox Code Playgroud)
接下来我使用了标准的 pandas 数据透视表函数:
pd.pivot_table(df1, values='Price', index='Status', columns='Category', aggfunc=np.sum)
pd.pivot_table(df2, values='Price', index='Status', columns='Category', aggfunc=np.sum)
Run Code Online (Sandbox Code Playgroud)
所以我有以下两个数据透视表作为输出:
地点1:
| 地位 | 家具 | 办公用品 |
|---|---|---|
| 新的 | 200 美元 | 300 美元 |
| 老的 | 50 美元 | 150 美元 |
地点2: …
我还没有收到其他功能的复制警告,并且我还没有找到解决它的方法。
这是我的代码:
div_df.loc[:,"Ann.Date"] = pd.to_datetime(div_df.loc[:,"Ann.Date"], format='%d %b %Y')
/volume1/homes/id/venv/lib/python3.8/site-packages/pandas/core/indexing.py:1843: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
self.obj[item_labels[indexer[info_axis]]] = value
Run Code Online (Sandbox Code Playgroud)
除了以下之外,我还没有找到其他解决方案:
div_df.loc[:,"Ann.Date"] = pd.to_datetime(div_df.loc[:,"Ann.Date"], format='%d %b %Y', errors='coerce')
Run Code Online (Sandbox Code Playgroud) 我正在尝试合并两个字符串列,并且希望摆脱'others'计数器值是否为“非其他”值 - 例如'apple' + 'others' = 'apple'but 'others' + 'others' = 'others'。我管理了第二个条件,但是如何在合并时适应这两个条件?
data = {'fruit1':["organge", "apple", "organge", "organge", "others"],
'fruit2':["apple", "others", "organge", "watermelon", "others"]}
df = pd.DataFrame(data)
df["together"] = df["fruit1"] + ' ' + df["fruit2"]
df["together"] = df["together"].apply(lambda x: ' '.join(pd.unique(x.split())))
fruit1 fruit2 together
0 organge apple organge apple
1 apple others apple others
2 organge organge organge
3 organge watermelon organge watermelon
4 others others others
Run Code Online (Sandbox Code Playgroud)
预期输出:
fruit1 fruit2 together
0 organge apple organge …Run Code Online (Sandbox Code Playgroud) 我在数据框中有一个布尔True/ False-列“ ”,例如:Mask
Mask
True
True
True
False
False
True
False
False
Run Code Online (Sandbox Code Playgroud)
现在我尝试添加一列,其中包含连续True/False行的计数,其中True是正和(计数为+1),False是负和(计数为-1),例如
Mask Count
True 3
True 3
True 3
False -2
False -2
True 1
False -2
False -2
Run Code Online (Sandbox Code Playgroud)
我尝试过groupby,sum但现在我脑子里有一个结。
尝试过类似的东西
mask.groupby((~mask).cumsum()).cumsum().astype(int)
Run Code Online (Sandbox Code Playgroud)
(是/mask的条件) 但这仅计算 True 并进行计数而不显示总和。TrueFalse
非常感谢任何建议!
我的数据框中有大约 1000 万行数据。下面是 2 行的示例。
| 指数 | 数量 | 借记卡信用卡 |
|---|---|---|
| 0 | 1000 | 1 |
| 1 | 2000年 | 2 |
我想编写一个函数来检查“借方/贷方”列中的值是借方 1 还是贷方 2。如果“金额”列中的数字为 2,则将其替换为负数。因此,例如,该表将更改为:
| 指数 | 数量 | 借记卡信用卡 |
|---|---|---|
| 0 | 1000 | 1 |
| 1 | -2000 | 2 |
这是我写的函数,但它对于 900 万行来说真的很慢。谁能告诉我如何重构这段代码?或者是否有更有效的方法来执行此任务?(使用 python 或 sql。最好是 python。)
def change_credits_to_negative(df):
for num in range(len(df)):
if df['debit/credit'].loc[num] == 2: # 1 is for debit & 2 is for credit
df['Amount'].loc[num] = -df['Amount'].loc[num]
Run Code Online (Sandbox Code Playgroud) 我有两个 Excel 电子表格。第一列有多个列,其中三列(名称不同)具有公共数据。我的第二个电子表格包含一个键以及我想要带入第一个电子表格的数据。例如:
表格1:
| 目标公司ID | 子公司ID | 母公司 ID |
|---|---|---|
| 1 | 2 | 3 |
表2:
| 公司编号 | 公司规模 |
|---|---|
| 1 | 小的 |
| 2 | 中等的 |
| 3 | 大的 |
使用 Excel,我会执行一系列 Vlookups,但表 1 很大,需要很长时间才能计算。我想生成一个表,例如:
| 目标公司ID | 目标尺寸 | 子公司ID | 子尺寸 | 母公司 ID | 父级尺寸 |
|---|---|---|---|---|---|
| 1 | 小的 | 2 | 中等的 | 3 | 大的 |
我已经尝试过pd.merge,但它不像为vlookup特定列分配值那样有针对性
pandas ×12
python ×12
dataframe ×6
python-3.x ×4
datetime ×1
numpy ×1
pivot-table ×1
regex ×1
time-series ×1
vlookup ×1