这和我昨天问的问题很相似。其目的是能够添加一个功能,允许根据另一个列中显示的值创建一个列。例如,当它在指定的文件中找到一个国家代码时,我希望它创建一个名为“country codeTotal”的列,并对具有相同国家代码的每行的单位数量求和
这是我的脚本目前的输出:
我想看到的是:
我的剧本:
df['Sum of Revenue'] = df['Units Sold'] * df['Dealer Price']
df['AR Revenue'] = df[]
df = df.sort_values(['End Consumer Country', 'Currency Code'])
# Sets first value of index by position
df.loc[df.index[0], 'Unit Total'] = df['Units Sold'].sum()
# Sets first value of index by position
df.loc[df.index[0], 'Total Revenue'] = df['Sum of Revenue'].sum()
# Sums the amout of Units with the End Consumer Country AR
df['AR Total'] = df.loc[df['End Consumer Country'] == 'AR', 'Units Sold'].sum()
# Sums the amount of Units with the End Consumer Country AU
df['AU Total'] = df.loc[df['End Consumer Country'] == 'AU', 'Units Sold'].sum()
# Sums the amount of Units with the End Consumer Country NZ
df['NZ Total'] = df.loc[df['End Consumer Country'] == 'NZ', 'Units Sold'].sum()
但是,由于我知道这个文件中会出现哪些国家,因此我将它们相应地添加到我的脚本中以查找。如何编写脚本,以便在找到另一个国家/地区代码(例如GB)时,创建一个名为“GB Total”的列,并将国家/地区代码设置为GB时每行的单位相加。你知道吗
任何帮助都将不胜感激!你知道吗
如果您真的需要这种格式,那么下面是我将如何继续(下面的起始数据):
输出:
df
:如您所见,
pandas
添加了一堆NaN
值,因为我们只给第一行赋值,而且DataFrame
必须是矩形的用一个不同的
DataFrame
来概括每个国家的总数和内部情况要简单得多。如果这是好的,那么一切都简化为一个.pivot_table
输出:
同样的信息,更容易编码。你知道吗
样本数据:
相关问题 更多 >
编程相关推荐