【问题标题】:Creating a new column with numbers in Pandas to group with a column with existing numbers在 Pandas 中创建一个带有数字的新列以与具有现有数字的列分组
【发布时间】:2018-11-22 19:48:50
【问题描述】:

早安,

我在这里有一个数据框中的列:

 A
 23
 10
 11 
 22

我的目标是创建一个新列并将数字关联如下:

A     file_number
23        8
10        6
11        6
22        8

如上所示,数字 22、23 与数字 8 相关联,数字 10 和 11 与数字 6 相关联。如何创建这样的列?在此先感谢

【问题讨论】:

  • Afile_number是什么关系?

标签: python pandas numpy dataframe data-structures


【解决方案1】:

我认为如果需要,需要通过字典的map 的第一个数字值创建新值:

print (df['A'].apply(type))
0    <class 'int'>
1    <class 'int'>
2    <class 'int'>
3    <class 'int'>
Name: A, dtype: object

df['new'] = (df['A'] // 10).map({1:6, 2:8})
print (df)
    A  new
0  23    8
1  10    6
2  11    6
3  22    8

详情

print ((df['A'] // 10))
0    2
1    1
2    1
3    2
Name: A, dtype: int64

另一种解决方案适用于字符串:

df['new'] = df['A'].astype(str).str[0].map({'1':6, '2':8})

print (df['A'].apply(type))
0    <class 'str'>
1    <class 'str'>
2    <class 'str'>
3    <class 'str'>
Name: A, dtype: object

df['new'] = df['A'].str[0].map({'1':6, '2':8})

如果需要将正数转换为第一个数字,可以使用this 转换为numpy/pandas 的解决方案:

df['new'] = df['A'] // 10 ** np.log10(df['A'].values).astype(int)

print (df)
        A  new
0       2    2
1   10000    1
2     110    1
3  220000    2

【讨论】:

  • 如果它有更多的值分组和一千行怎么办? @jezrael
  • @DeepakM - 将它们添加到dictionary
  • 啊,我明白了。谢谢。最后,有没有更短的方法,而不是写出.map 中的所有步骤。如果我使用更大的数据框将很多数字分组为一个数字并且有几种情况怎么办。有没有办法索引或切片或其他方式......? @jezrael
  • @DeepakM - 如果需要良好的性能解决方案 map 由 ditiioanry 提供。你理解正确吗,df['A'] // 10 是不可能使用的,因为像456417 这样的数字长度不同?
猜你喜欢
  • 2021-11-25
  • 1970-01-01
  • 2023-03-04
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
  • 2022-06-14
  • 2021-11-01
相关资源
最近更新 更多