社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Corralien

Corralien 最近创建的主题
Corralien 最近回复了
3 年前
回复了 Corralien 创建的主题 » 对于循环python-按年份和按分组操作

按年份和流域名称分组,而不是仅按流域名称分组?

out = rainfall_watershed.groupby(['year', 'WATERSHED_NAME', as_index=False)['inches'].sum()
3 年前
回复了 Corralien 创建的主题 » 在Linux上以root用户身份获取Python中的主目录路径

使现代化 后编辑。

使用 os.environ 得到 SUDO_USER 变量或作为回退 USERNAME .

剧本 test.py :

import os

username = os.environ.get('SUDO_USER', os.environ.get('USERNAME'))
print(os.path.expanduser(f'~{username}'))

执行:

$ python test.py
/home/louis

$ sudo python test.py
/home/louis

从…起 man sudo :

SUDO_USER设置为调用SUDO的用户的登录名。


老生常谈 在编辑之前。

使用 os.path.expanduser :)

>>> os.path.expanduser('~louis')
/home/louis
3 年前
回复了 Corralien 创建的主题 » 如何根据规则编辑python数据框的字符串类型列?

你可以用 str.replace :

df['GEO'] = df['GEO'].str.replace('POINT\s+\((.*)\s+(.*)\)', r'(\2, \1)', regex=True)
print(df)

# Output
          NAME                                        GEO
0        Paris                           (48.85, 2.31647)
1     New York        (40.731499671618, -73.993457389558)
2          Rio                             (-22.9, -43.2)
3  Airport GRU  (-23.429382262746415, -46.47313507388693)
4         ORLY                   GEOMETRYCOLLECTION EMPTY
3 年前
回复了 Corralien 创建的主题 » Python Pandas在设置了最大列数和行宽后仍会打印省略号

你没有使用正确的选项。

从文件中:

陈列max_colwidth设置列的最大宽度。此长度或更长的单元格将被省略号截断。

陈列max_colwidth:int或None 报表中一列的最大字符宽度 数据结构。当列溢出时,会出现“…” 占位符嵌入到输出中。“无”值表示无限制。 [默认值:50][当前值:50]

pd.set_option('display.max_colwidth', None)
print(df)

# Output
0  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua

尝试:

def sample(df1, df2, num):
    df1_list = [] 
    df2_list = []
    for x in range(1, num+1):
        df1_list.append(df1.sample(n=num))
        df2_list.append(df2.sample(n=num))
    combined_list = df1_list + df2_list
    Baby = pd.concat(combined_list)
    return Baby

# I don't use copy() here because I don't modify E_df or M_df
baby = sample(E_df, M_df, 50)
3 年前
回复了 Corralien 创建的主题 » python:解析以冒号分隔的格式化字符串

创建一个 iterator 在你的绳子上:

message = '1:4:a:5:6:7:2:10:72:75:63:6f:6e:74:72:6f:6c:6c:65:72:2e:6f:72:67'

code = iter(message.split(':'))
data = {}

for t in code:
    l = int(next(code), 16)
    d = [next(code) for _ in range(l)]
    data[t] = d

输出:

>>> data
{'1': ['a', '5', '6', '7'],
 '2': ['72', '75', '63', '6f', '6e', '74', '72', '6f', '6c', '6c', '65', '72', '2e', '6f', '72', '67']}
3 年前
回复了 Corralien 创建的主题 » Django如何使用函数return设置基于类的视图查询集

也许你应该放弃 get_queryset 方法A. queryset 这不是一个 context 格言:

class ProductsView(ListView):

    paginate_by = 20
    context_object_name = 'products'
    template_name = "urunler.html"

    def get_queryset(self):
        queryset = super().get_queryset()

        # do stuff here to change queryset dynamically
        ...

        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # do stuff here to update your context dict
        ...

        return context

尝试 str.findall :

df['0s'] = df['Sequence'].str.findall('^0*').str[0].str.len()
print(df)

# Output:
    Sequence  0s
0  012312312   1
1  024624624   1
2  036901357   1
3  002486248   2
4  045074305   1
5  080666140   1
3 年前
回复了 Corralien 创建的主题 » 计算给定区域(特定行*列)中大于0的值-Python、Excel、Pandas

使用布尔掩码并求和:

N = sum((df['Participant'] == 1) & (df['Condition'] == 1) & (df['RT'].notna()))
print(N)

# Output
1

细节:

m1 = df['Participant'] == 1
m2 = df['Condition'] == 1
m3 = df['RT'].notna()
df[['m1', 'm2', 'm3']] = pd.concat([m1, m2, m3], axis=1)
print(df)

# Output
   Participant  Condition    RT     m1     m2     m3
0            1          1  0.10   True   True   True  # All True, N = 1
1            1          1   NaN   True   True  False
2            1          2  0.48   True  False   True
3            2          1  1.20  False   True   True
4            2          2   NaN  False  False  False
5            2          2  0.58  False  False   True
3 年前
回复了 Corralien 创建的主题 » 尝试使用python删除列中没有数值的所有行

使用 pd.numeric 作为布尔掩码:

df = df.loc[pd.to_numeric(df['age'], errors='coerce').notna()]
print(df)

# Output
  age
0  55
1  45
2  58

所有非数值都将转换为 NaN .

使用 explode :

cols = ['Summoner', 'Traits', 'Record_ID']
out = df.assign(Record_ID='id_' + df['Rank'].astype(str))[cols] \
        .explode('Traits', ignore_index=True) \
        .rename(columns={'Traits': 'Trait'})
print(out)

# Output:
   Summoner          Trait Record_ID
0     name1    7 Innovator      id_1
1     name1  1 Transformer      id_1
2     name1    3 Enchanter      id_1
3     name1    2 Socialite      id_1
4     name1    2 Clockwork      id_1
5     name1      2 Scholar      id_1
6     name1        2 Scrap      id_1
7     name2       1 Cuddly      id_2
8     name2      1 Glutton      id_2
9     name2    5 Mercenary      id_2
10    name2      4 Bruiser      id_2
11    name2     6 Chemtech      id_2
12    name2      2 Scholar      id_2
13    name2    1 Socialite      id_2
14    name2     2 Twinshot      id_2
4 年前
回复了 Corralien 创建的主题 » Python中分组值计数条形图的子图

这是你所期待的吗?

import matplotlib.pyplot as plt

fig, axs = plt.subplots(5, 5, sharex=True, sharey=True, figsize=(15, 15))
for ax, (district, sr) in zip(axs.flat, g.groupby('RESPONSIBLE DISTRICT')):
    ax.set_title(district)
    ax.plot(sr.index.get_level_values('YEAR'), sr.values)
fig.tight_layout()

plt.show()

production.png

3 年前
回复了 Corralien 创建的主题 » python基于其他列值设置列的值

你可以用 np.where :

df['price_diff'] = np.where(df['side'] == 0,
                            df['ref_price'] * df['price'],
                            df['ref_price'] * df['price'] * -1)
print(df)

# Output
   side  ref_price  price  price_diff
0     0        100    110       11000
1     1        110    100      -11000
3 年前
回复了 Corralien 创建的主题 » 无法在python上使用replace方法

你只需要创造 raw strings (前缀) 'r' )

rolechange = {r"\\Adv":"Adversary",
              r"\\Sci":"Scientist",
              r"\\Inn":"Innocent",
              r"\\Und":"Undetermined"}

>>> df['Role Type'].replace(rolechange)

0       Scientist
1        Innocent
2    Undetermined
Name: Role Type, dtype: object

可能有点慢,因为你的数据很乱:

  • 空行
  • 空口述
  • 字符串值

尝试:

def f_max(d):
    k = v = ''
    if d:
        d = {k: v for k, v in d.items() if isinstance(v, (int, float))}
        if d:
            k = max(d, key=d.get)
            v = d[k]
    return pd.Series({'Name': k, 'Value': v})

df = pd.concat([df, df['Obj_values'].apply(f_max)], axis=1)

输出:

>>> df
                                          Obj_values  Name Value
0               {'Sony': 25, 'Max': 91, 'James': 55}   Max    91
1                            {'Jack': 12, 'Max': 10}  Jack    12
2                                                 {}            
4                                                               
5                           {'Halk': 21, 'Hall': 15}  Halk    21
6                                           {'H': 1}     H     1
7                 {'Aws': 'k', 'Az': 113, 'Gc': 'b'}    Az   113
8  {'Max': 60, 'HBO': 113, 'Sony': 55, 'WS': 1256...    WS  1256
3 年前
回复了 Corralien 创建的主题 » 如何将列表列表添加到Python上特定列的df中?熊猫相关

您可以使用理解来提取列表中每个项目的第一个也是唯一一个元素:

df['Volatility expected'] = [v[0] for v in volatility_list]
print(df)

# Output
    Time Currency       Volatility expected                                 Event Actual Forecast Previous
0  02:00      GBP   Low Volatility Expected  U.K. Construction Output (YoY) (Jan)   9.9%     9.2%     7.4%
1  02:00      GBP   Low Volatility Expected       Construction Output (MoM) (Jan)   1.1%     0.5%     2.0%
2  02:00      GBP  High Volatility Expected                             GDP (MoM)   0.8%     0.2%    -0.2%
3  02:00      GBP  High Volatility Expected                             GDP (YoY)  10.0%     9.3%     6.0%
3 年前
回复了 Corralien 创建的主题 » 如何在Python中正确地减去矩阵?

也许这会有帮助:

rng = np.random.default_rng(2022)
df = pd.DataFrame(rng.integers(0, 10, (5, 4)))
sr = pd.Series(rng.integers(0, 10, (5, )))
>>> df
   0  1  2  3
0  7  2  7  0
1  1  6  9  0
2  0  6  8  7
3  8  1  5  0
4  0  4  8  9

>>> sr
0    3
1    9
2    0
3    2
4    6
dtype: int64

>>> df - sr  # does not work
   0  1  2  3   4
0  4 -7  7 -2 NaN
1 -2 -3  9 -2 NaN
2 -3 -3  8  5 NaN
3  5 -8  5 -2 NaN
4 -3 -5  8  7 NaN

>>> df.sub(sr, axis=0)  # work
   0  1  2  3
0  4 -1  4 -3
1 -8 -3  0 -9
2  0  6  8  7
3  6 -1  3 -2
4 -6 -2  2  3
3 年前
回复了 Corralien 创建的主题 » Python:如何根据列的唯一值对列名称进行分组?

使用 pivot :

out = df.pivot(index='case', columns='val', values='val')
out.columns = [f'val{i}' for i in range(len(out.columns))]
>>> out
     val0 val1 val2
case               
0       x    y    z
1       x  NaN    z
2     NaN    y  NaN