提问者:小点点

如何复制选定的Pandas数据,并用不同的列名复制它?


当前代码:

import pandas as pd

data = pd.read_csv(r'Data.csv', sep=',', encoding='latin-1')

col = data.loc[data['Customer Code'] == '001']
print(col)

它的作用

这将获得客户代码等于001的所有数据

我怎样才能

我可以怎样做:

  • 获取所有返回数据
  • 将返回的数据追加到相同的CSV
  • 追加时,使用其他列名,例如111

示例

当前数据

Customer Code, Name
001, Customer 1
001, Customer 1
001, Customer 1
002, Customer 2
003, Customer 3

所需数据选择客户代码001的数据

Customer Code, Name
001, Customer 1
001, Customer 1
001, Customer 1
002, Customer 2
003, Customer 3
111, Customer 1 --Pasted from 001, but changed the customer code
111, Customer 1 --Pasted from 001, but changed the customer code
111, Customer 1 --Pasted from 001, but changed the customer code

共1个答案

匿名用户

下面的代码获取预期的输出。 这里,111是通过向现有的customer_code添加110得到的。 这行代码可能会被改变以使用不同的编号方案。

# Import library
import pandas as pd
import numpy as np

# Create DataFrame
df = pd.DataFrame({
    'Customer_Code':['001','001', '001', '002', '003'],
    'Name': ['Customer 1','Customer 1','Customer 1','Customer 2','Customer 3']
})

# Set counter for new label
counter = 110

# Create new labels
temp = df[['Customer_Code']]
temp['Name'] = df.apply(lambda x: x['Name']+' --Pasted from '+ x['Customer_Code'] + ', but changed the customer code', axis=1)
temp['new_code'] = (df['Customer_Code'].astype(int) + counter).astype(str)
temp = temp[['new_code','Name']].rename(columns={'new_code':'Customer_Code'})

# Join new labels to original DataFrame
df = df[['Customer_Code','Name']]
df = pd.concat([df, temp], axis=0)

# Output
print(df)

输出量

注意:name列中的数据是右对齐的,而不是如问题中预期输出所示的左对齐。

  Customer_Code                                               Name
0           001                                         Customer 1
1           001                                         Customer 1
2           001                                         Customer 1
3           002                                         Customer 2
4           003                                         Customer 3
0           111  Customer 1 --Pasted from 001, but changed the ...
1           111  Customer 1 --Pasted from 001, but changed the ...
2           111  Customer 1 --Pasted from 001, but changed the ...
3           112  Customer 2 --Pasted from 002, but changed the ...
4           113  Customer 3 --Pasted from 003, but changed the ...