小编Zub*_*ubo的帖子

如何设置pi的倍数(Python)(matplotlib)

我想在Python中制作一个情节,并且x范围显示为pi的倍数.

有没有一个很好的方法来做到这一点,而不是手动?

我正在考虑使用matplotlib,但其他选项都很好.

编辑3:EL_DON的解决方案对我有用:

import matplotlib.ticker as tck
import matplotlib.pyplot as plt
import numpy as np

f,ax=plt.subplots(figsize=(20,10))
x=np.linspace(-10*np.pi, 10*np.pi,1000)
y=np.sin(x)

ax.plot(x/np.pi,y)

ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0))

plt.style.use("ggplot")


plt.show()
Run Code Online (Sandbox Code Playgroud)

赠送:

很好的正弦图

编辑2(在编辑3中解决!):EL_DON的答案似乎不适合我:

import matplotlib.ticker as tck
import matplotlib.pyplot as plt
import numpy as np

f,ax=plt.subplots(figsize=(20,10))
x=np.linspace(-10*np.pi, 10*np.pi)
y=np.sin(x)

ax.plot(x/np.pi,y)

ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0))

plt.style.use("ggplot")

plt.show()
Run Code Online (Sandbox Code Playgroud)

给我

情节

哪个看起来不对劲

python plot matplotlib axis-labels

12
推荐指数
4
解决办法
1万
查看次数

关闭时运行 Google Sheets 脚本

我想在我的 Google Sheet 中使用一个触发器,类似于onOpen(),但在我关闭工作表时触发。但是,我没有在 Google API 指南中找到类似的内置内容,也没有其他人发布的任何内容,并且不确定如何编写。有什么帮助吗?

google-sheets google-apps-script

5
推荐指数
1
解决办法
4833
查看次数

Python:YAML 函数字典:如何加载而不转换为字符串

我有一个 YAML 配置文件,其中包含一个字典,如下所示:

"COLUMN_NAME": column_function
Run Code Online (Sandbox Code Playgroud)

它将字符串映射到函数(存在并且应该被调用)。

但是,当我使用 加载它时yaml,我看到加载的字典现在将字符串映射到字符串:

'COLUMN_NAME': 'column_function' 
Run Code Online (Sandbox Code Playgroud)

现在我不能按预期使用它 -'column_function'不指向column_function.

加载 mydict以便映射到我的函数的好方法是什么?在对这个问题进行了一些搜索和阅读之后,我对使用eval或类似的东西非常谨慎,因为配置文件是用户编辑的。

我认为这个线程是关于我的问题,但我不确定解决它的最佳方法。

  • getattr并且setattr我认为是因为它们对实例化的对象进行操作,而我有一个简单的脚本。
  • globals()vars()locals()为我提供dicts 个变量,我想我应该globals()根据this 使用

我应该为我的配置中的每个键值对查找其中的字符串dict吗?这是一个好方法吗:

for (key, val) in STRING_DICTIONARY.items():
    try: 
        STRING_DICTIONARY[key] = globals()[val]   
    except KeyError:
        print("The config file specifies a function \"" + val 
               + "\" for column \"" + key 
               + "\". No such function …
Run Code Online (Sandbox Code Playgroud)

python string dictionary yaml python-3.x

5
推荐指数
1
解决办法
3989
查看次数

Why can't I get the type of a Pandas cell from a function?

I'd like to get the type of argument I'm passing to a function (I think it's a Pandas Series, but I want to make sure) and write into a new column in a Pandas Dataframe. Why does this

data = np.array([['','Col1','Col2', 'Col3'],
                ['Row1','cd, d', '1, 2', 'ab; cd'],
                ['Row2','e, f', '5, 6', 'ef; gh'],
                ['Row3','a, b', '3, 4', 'ij; kl']])

df = pd.DataFrame(data=data[1:,1:],
                  index=data[1:,0],
                  columns=data[0,1:])

def find_type(my_arg):
    return type(my_arg)

df['types'] = find_type(df['Col1'])
Run Code Online (Sandbox Code Playgroud)

give me

AttributeError: 'int' object has no …
Run Code Online (Sandbox Code Playgroud)

python pandas

4
推荐指数
2
解决办法
3217
查看次数

逐行逐个比较2个Pandas数据帧

我有2个数据帧,df1df2希望执行以下操作,将结果存储在df3:

for each row in df1:

    for each row in df2:

        create a new row in df3 (called "df1-1, df2-1" or whatever) to store results 

        for each cell(column) in df1: 

            for the cell in df2 whose column name is the same as for the cell in df1:

                compare the cells (using some comparing function func(a,b) ) and, 
                depending on the result of the comparison, write result into the 
                appropriate column of the "df1-1, df2-1" …
Run Code Online (Sandbox Code Playgroud)

python iteration iterator dataframe pandas

3
推荐指数
1
解决办法
2257
查看次数

如何检查 Pandas 行是否包含空集

我想检查 Pandas Dataframe 行的特定列中是否包含空集,即

d = {'col1': [1, 2], 'col2': [3, {}]}
df2 = pd.DataFrame(data=d)


    col1    col2
0   1       3
1   2       {}
Run Code Online (Sandbox Code Playgroud)

进而

df2['col_2_contains_empty_set'] = ? #  how to implement this
Run Code Online (Sandbox Code Playgroud)

应该给

    col1    col2    col_2_contains_empty_set
0   1       3       False
1   2       {}      True
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?做不到

bool(df['col2']) 
Run Code Online (Sandbox Code Playgroud)

或者

df['col2'].bool()
Run Code Online (Sandbox Code Playgroud)

我认为它们Series具有模糊的布尔值。

python boolean pandas

3
推荐指数
1
解决办法
2万
查看次数

连接字符串列和索引

我有一个DataFrame这样的:

A    B
----------
c    d
e    f
Run Code Online (Sandbox Code Playgroud)

我想引入第三列,由和索引串联而成,这样就变成ABDataFrame

A    B    C
---------------
c    d    cd0
e    f    ef1
Run Code Online (Sandbox Code Playgroud)

我想这样做:

df['C'] = df['A'] + df['B'] + # and here I don't know how to reference the row index. 
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

python string concatenation dataframe pandas

2
推荐指数
1
解决办法
3197
查看次数

Pandas:使用 pd.at 和条件选择单元格值

我想从 Pandas 数据框中选择特定的单元格值。我想过滤掉 A 列中具有特定值的行,然后从 B 列中获取值。

据我了解,正确的方法是使用df.at,所以我尝试过

df.at(df['Column A' == column_A_value]['Column B'])
Run Code Online (Sandbox Code Playgroud)

但这行不通。我也尝试过,作为黑客,

str(['Column A' == column_A_value]['Column B'])
Run Code Online (Sandbox Code Playgroud)

也不行。

这样做的正确方法是什么?

编辑:

我想做的是输出更大循环内的值,例如:

while condition:
    for val in some_column_A_values:
        print("{},{}".format('stuff', df.at(df['Column A' == val]['Column B'])), file=myfile)
Run Code Online (Sandbox Code Playgroud)

python pandas

2
推荐指数
1
解决办法
9126
查看次数

python:使用文件句柄打印文件的内容

我遵循以下建议: 文件作为argparse的命令行参数 - 如果参数无效 以打印文件内容,则出现错误消息.这是一个MWE:

import argparse
import os


def is_valid_file(parser, arg):
    """

    :rtype : open file handle
    """
    if not os.path.exists(arg):
        parser.error("The file %s does not exist!" % arg)
    else:
        return open(arg, 'r')  # return an open file handle


parser = argparse.ArgumentParser(description='do shit')
parser.add_argument("-i", dest="filename", required=True,
                    help="input file with two matrices", metavar="FILE",
                    type=lambda x: is_valid_file(parser, x))

args = parser.parse_args()

print(args.filename.read)
Run Code Online (Sandbox Code Playgroud)

但是,我得到的不是文件内容:

<built-in method read of _io.TextIOWrapper object at 0x7f1988b3bb40>
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

python filehandle argparse

1
推荐指数
1
解决办法
527
查看次数