我主要在 Spyder 中使用 Python 进行数据科学。Visual Studio Code 和虚拟环境对我来说都是相当陌生的。
无论如何,我尝试使用 Visual Studio Code 中的终端在环境之间切换。我已经尝试过conda activate venv和activate venv。我没有收到错误消息,但使用conda env list查看哪个环境处于活动状态时我似乎陷入了Base。
在 Anaconda Prompt 中做同样的事情,我可以在环境之间切换。
我使用 Windows,并从 Anaconda Navigator 启动 Visual Studio Code。
到底是怎么回事?
我有一个根据id-column分组的数据框。对于每个组,我想获取包含最大值的行(整行,而不仅仅是值)。我可以通过首先获取每个组的最大值,然后创建一个过滤器数组,然后在原始数据帧上应用过滤器来做到这一点。像这样,
import pandas as pd
# Dummy data
df = pd.DataFrame({'id' : [1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4],
'other_value' : ['a', 'e', 'b', 'b', 'a', 'd', 'b', 'f' ,'a' ,'c', 'e', 'f'],
'value' : [1, 3, 5, 2, 5, 6, 2, 4, 6, 1, 7, 3]
})
# Get the max value in each group
df_max = df.groupby('id')['value'].max()
# Create row filter
row_filter = [df_max[i]==v for i, v in zip(df['id'], df['value'])]
# …Run Code Online (Sandbox Code Playgroud) 我从一些随机日期创建了一个系列
import pandas as pd
from datetime import datetime
pd.Series([datetime(2012, 8, 1), datetime(2013, 4, 1), datetime(2013, 8, 1)])
Out[49]:
0 2012-08-01
1 2013-04-01
2 2013-08-01
dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)
但是,如果我用 a 创建一个系列datetime.max,该系列的 dtype 突然变成了一个对象
pd.Series([datetime(2012, 8, 1), datetime(2013, 4, 1), datetime.max])
Out[50]:
0 2012-08-01 00:00:00
1 2013-04-01 00:00:00
2 9999-12-31 23:59:59.999999
dtype: object
Run Code Online (Sandbox Code Playgroud)
日期的显示方式也发生了变化。我想后一点与该系列现在是一个对象的事实有关。
datetime.max 与其他日期的类型相同
type(datetime.max)
Out[53]: datetime.datetime
type(datetime(2014, 1,1))
Out[54]: datetime.datetime
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?如何创建包含 'max'-datetime 值的系列?像这样
0 2012-08-01
1 2013-04-01
2 9999-12-31
dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud) 我想找到特定日期的"最接近"的月末日期.例如,如果日期是4.3.2017,28.2.2017则是最接近的日期.因为20.3.2017,31.3.2017是最接近的日期.对于陷入死亡中心的日期,如果我们选择更低或更高的日期并不重要.
从这两个帖子中,我如何获得一个月的最后一天?并且从列表中找到最接近的时间,我已经能够将以下方法拼凑在一起
public static DateTime findNearestDate(DateTime currDate)
{
List<DateTime> dates = new List<DateTime> { ConvertToLastDayOfMonth(currDate.AddMonths(-1)), ConvertToLastDayOfMonth(currDate) };
DateTime closestDate = dates[0];
long min = long.MaxValue;
foreach (DateTime date in dates)
if (Math.Abs(date.Ticks - currDate.Ticks) < min)
{
min = Math.Abs(date.Ticks - currDate.Ticks);
closestDate = date;
}
return closestDate;
}
public static DateTime ConvertToLastDayOfMonth(DateTime date)
{
return new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
}
Run Code Online (Sandbox Code Playgroud)
这很有效,但似乎有很多代码可以完成这么简单的任务.有人知道更简单,更紧凑的方法吗?
更新到 pandas v0.25.2 后,对大型数据帧上的许多列执行 groupby 的脚本不再有效。我收到内存错误
MemoryError: Unable to allocate array with shape (some huge number...,) and data type int64
Run Code Online (Sandbox Code Playgroud)
做了一些研究,我发现早期版本的 Git 报告了问题 (#14942)
import numpy as np
import pandas as pd
df = pd.DataFrame({
'cat': np.random.randint(0, 255, size=3000000),
'int_id': np.random.randint(0, 255, size=3000000),
'other_id': np.random.randint(0, 10000, size=3000000),
'foo': 0
})
df['cat'] = df.cat.astype(str).astype('category')
# killed after 6 minutes of 100% cpu and 90G maximum main memory usage
grouped = df.groupby(['cat', 'int_id', 'other_id']).count()
Run Code Online (Sandbox Code Playgroud)
运行此代码(在 0.25.2 版上)也会出现内存错误。我做错了什么(pandas v0.25 中的语法是否发生了变化?),或者是否返回了这个标记为已解决的问题?
请考虑以下示例.我用ToString()方法定义一个结构
public struct InnerStruct
{
public double a;
public double b;
public override string ToString()
{
return $"InnerStruct:\n" +
$" a: {a}\n" +
$" b: {b}";
}
}
Run Code Online (Sandbox Code Playgroud)
调用 ToString()
var i = new InnerStruct(){a=1, b=2};
i.ToString()
@"InnerStruct:
a: 1
b: 2
"
Run Code Online (Sandbox Code Playgroud)
因此,它ToString()提供了一个漂亮且可读的字符串,其中a和b缩进了四个空格.但是,假设我有一个新结构
public struct OuterStruct
{
public double c;
public InnerStruct inner;
public override string ToString()
{
return $"OuterStruct:\n" +
$" c: {c}\n" +
$" inner: {inner.ToString()}";
}
}
Run Code Online (Sandbox Code Playgroud)
现在写作 …
我正在尝试自动将数百个 Excel 文件读入单个数据帧。值得庆幸的是,Excel 文件的布局相当稳定。它们都有相同的标题(标题的大小写可能会有所不同),当然还有相同的列数,并且我想要读取的数据始终存储在第一个电子表格中。
但是,在某些文件中,在实际数据开始之前已经跳过了许多行。实际数据之前的行中可能有也可能没有注释等。例如,在某些文件中,标头位于第 3 行,然后数据从第 4 行及其下方开始。
我想pandas自己计算出要跳过多少行。目前我使用一个有点复杂的解决方案...我首先将文件读入数据帧,检查标题是否正确,如果没有搜索找到包含标题的行,然后重新读取文件,现在知道有多少行跳过..
def find_header_row(df, my_header):
"""Find the row containing the header."""
for idx, row in df.iterrows():
row_header = [str(t).lower() for t in row]
if len(set(my_header) - set(row_header)) == 0:
return idx + 1
raise Exception("Cant find header row!")
my_header = ['col_1', 'col_2',..., 'col_n']
df = pd.read_excel('my_file.xlsx')
# Make columns lower case (case may vary)
df.columns = [t.lower() for t in df.columns]
# Check if the header of the dataframe mathces …Run Code Online (Sandbox Code Playgroud)