社区所有版块导航
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
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

richardec

richardec 最近创建的主题
richardec 最近回复了
3 年前
回复了 richardec 创建的主题 » 如何将行值列表和列名列表与python结合起来?[重复]

你可以用 data[0::4] 从第一项开始,每四项选择一项, data[1::4] 从第二项开始,每隔第四项进行选择,依此类推。然后,将它们放入数组并使用 dict + zip 使用该数组和列并将其传递给 pd.DataFrame :

df = pd.DataFrame(dict(zip(columns, [data[0::4], data[1::4], data[2::4], data[3::4]])))

输出:

>>> df
      Name  Age     City  Score
0     jack   34   Sydney  155.0
1     Riti   31    Delhi  177.5
2     Aadi   16   Mumbai   81.0
3    Mohit   31    Delhi  167.0
4    Veena   12    Delhi  144.0
5  Shaunak   35   Mumbai  135.0
6    Shaun   35  Colombo  111.0
3 年前
回复了 richardec 创建的主题 » 如果python中有两个不同的符号,如何在dataframe中拆分数据?

.str.replace 我能为你做到这一点:

df['Gross'] = df['Gross'].str.replace('^[^\d]+|[^\d]+$', '', regex=True).astype('float')

输出:

>>> df['Gross']
0     0.43  
1     142.50
2     858.37
3     335.45
4     316.83
5     165.36
6     27.33 
7     27.33 
8     426.83
9     53.37 
10    0.35  
11    0.35  
12    108.10
13    515.20
14    390.53
15    390.53
16    543.64
17    159.23
18    159.23
19    159.23
20    12.14 
21    117.62
22    7.74  
23    7.74  
24    56.85 
25    7.00  
26    7.00  
27    96.85 
28    0.40  
Name: Gross, dtype: float64
3 年前
回复了 richardec 创建的主题 » 数据操作——Python

这应该是有效的:

part1 = df[['COL_1', 'COL_2']].set_axis([0,1,2], axis=1)
part2 = df[['COL_1', 'COL_4']].set_axis([0,1,2], axis=1)
new_df = pd.concat([part1, part2], ignore_index=True)
new_df[3] = new_df[1]
new_df.columns = ['COL_1', 'COL_8', 'COL_9', 'COL_10']

输出:

>>> new_df
  COL_1 COL_8 COL_9 COL_10
0     A  col2  col3   col2
1     B  col2  col3   col2
2     C  col2  col3   col2
3     A  col4  col5   col4
4     B  col4  col5   col4
5     C  col4  col5   col4
3 年前
回复了 richardec 创建的主题 » 在Python中如何将列表中的一个字符串元素拆分为两个?

我会使用列表理解来拆分每个字符串,然后将其传递给 pd.DataFrame :

lst = ['Fred Green,20/11/2020\n', 'Jack Wilson,01/05/2021\n',]

df = pd.DataFrame([item.strip().split(',') for item in lst], columns=['name', 'date'])

输出:

>>> df
          name        date
0   Fred Green  20/11/2020
1  Jack Wilson  01/05/2021

你先 groupby(['id', 'key']) agg(list) ,可以按索引的第一级进行分组,对于每组,使用 droplevel + to_dict :

new_df = df.groupby(['id', 'key']).agg(list).groupby(level=0).apply(lambda x: x['value'].droplevel(0).to_dict()).reset_index(name='value')

输出:

>>> new_df
   id                              value
0   1  {'a': ['kkk', 'aaa'], 'b': ['5']}
1   2         {'a': ['kkk'], 'b': ['8']}

或者更简单一点:

new_df = df.groupby('id').apply(lambda x: x.groupby('key')['value'].agg(list).to_dict())
3 年前
回复了 richardec 创建的主题 » Python字典。get-TypeError:不可损坏的类型:“Series”

pd.Series.map 非常适合这个。

df['AC'].astype(str).map(dict_wu)

结合其他代码:

df['test'] = np.where(df['AC'].astype(str).map(dict_wu) == df['Units'], True, False)

输出:

>>> df
      AC Units   test
2   1002    UG  False
3   1004    MG  False
6   1004    UG   True
7   1005    UG  False
91  1028    MG   True
92  1028    UG  False
93  1028    UG  False
3 年前
回复了 richardec 创建的主题 » 基于nd数组和1d数组的if-else条件创建数据帧的Pythonic方法

使用如何 x if cond else y 三元语法?

def main_fn(arr_1):
    all_result_summary = []
    for method in ["met_1", "met2", "met_3"]:
        results: ndarray = np.array(main_fn(list(arr_1), method))
        all_result_summary.append(
            pd.DataFrame(
                {
                    "Method": method,
                    "result": results.mean(),
                    "result_sd_ax_0": results.std(ddof=1) if method == "met_3" else results.mean(axis=0).std(ddof=1),
                    "result_sd_ax_1": "NA" if method == "met_3" else results.mean(axis=1).std(ddof=1),
                },
                index=[0],
            )
        )
        summary = pd.concat(all_result_summary, axis=0, ignore_index=True)
    return summary
3 年前
回复了 richardec 创建的主题 » 每次出错时,如何在python中使用where方法?

我不确定是什么 are.equal_to 是的,但这应该对你有用:

fastball = march[march["TaggedPitchType"] == "Fastball"]
3 年前
回复了 richardec 创建的主题 » 如何删除df列python中最后一个句点之后的字符?

这应该是有效的:

df['col'] = df['col'].str.rsplit('.', n=1).str[0].str.split('.').str[-1]

输出:

>>> df
           col
0  common_name
1       amazon
2       amazon
3       amazon
4      walmart
5      walmart
6     michigan
3 年前
回复了 richardec 创建的主题 » 如何使用python将for循环输出数据帧合并为一个?

矢量化(读作“更快”)解决方案:

a = np.array(dfa['A'].str.split('').str[1:-1].tolist())
b = np.array(dfb['B'].str.split('').str[1:-1].tolist())

dfb[['disB_1', 'disB_2', 'disB_3']] = (a != b[:, None]).sum(axis=2)

输出:

>>> dfb
    B  disB_1  disB_2  disB_3
0  AC       1       2       1
1  BC       2       1       1
2  CC       2       2       0
3 年前
回复了 richardec 创建的主题 » Pandas,Python-合并具有相同键但具有不同值的列

用口述把它传给 pd.DataFrame :

dct = {
    'key': pd.Series(key),
    'index0': pd.Series(index0),
    'index1': pd.Series(index1),
    'index2': pd.Series(index2),
}

df = pd.DataFrame(dct)

输出:

>>> df
      key  index0  index1  index2
0  1234.0       1       4       9
1  2345.0       4       3       4
2  2223.0       6       2       6
3  6578.0       3       1       4
4  9976.0       4       6       3
5     NaN       5       8       2
6     NaN       6       5       1
7     NaN       2       3       4
8     NaN       1       1       1
3 年前
回复了 richardec 创建的主题 » Python-编码后反转原始值

试试这个:

new_df = df.drop(['Level'], axis=1).pivot(columns='Code', index='ID').fillna('').droplevel(0, axis=1).rename_axis(None, axis=1)

输出:

>>> new_df
     Q1    Q2     Q3    Q4      Q5        Q6
ID                                          
1   0.0                                     
2        11.0                               
3              100.0                        
4                     50.0                  
5                           1000.0          
6                                   122000.0