簡體   English   中英

根據另一列的值將列添加到pandas數據框中

[英]Adding columns to a pandas dataframe based on values of another column

這是我正在進行的一系列問題的一部分,我正在嘗試根據每個客戶收到的醫療服務數量來壓縮多行csv文件。 對於每種服務,它們都有一行。 我在底部包括了數據框。

我正在嘗試計算客戶機(用ID_profile號標識)獲得每種服務的次數,並將其添加到以服務類型命名的列中。 因此,如果客戶獲得3個早期干預服務,我將在“ eisserv”列中添加數字“ 3”。 完成之后,我想將所有客戶端行合並為一個。

我陷入困境的地方是根據一列數據填充3個不同的列。 我正在嘗試使用一些字符串來比較要比較的行。 該函數有效,但是由於我無法理解的原因,該函數正常工作時所有字符串都變為“ 25”。

import pandas as pd
df = pd.read_csv('fakeRWclient.csv')

df['PrimaryServiceCategory'] = df['PrimaryServiceCategory'].map({'Referral for Health Care/Supportive Services': '33', 'Health Education/Risk reduction': '25', 'Early Intervention Services (Parts A and B)': '11'})

df['ServiceDate'] = pd.to_datetime(df['ServiceDate'], format="%m/%d/%Y")
df['id_profile'] = df['id_profile'].apply(str)
df['served'] = df['id_profile']  + " " + df['PrimaryServiceCategory']

df['count'] = df['served'].map(df['served'].value_counts())
eis = "11"
ref = "33"
her = "25"
print("Here are the string values")
print(eis)
print(ref)
print(her)
df['herrserv']=""
df['refserv']=""
df['eisserv']=""
for index in df.itertuples():
    for eis in df['PrimaryServiceCategory']:
        df['eisserv'] = df['count']
    for her in df['PrimaryServiceCategory']:
        df['herrserv'] = df['count']
    for ref in df['PrimaryServiceCategory']:
        df['refserv'] = df['count']
print("Here are the string values")
print(eis)
print(ref)
print(her)

這是輸出:

Here are the string values
11
33
25
Here are the string values
25
25
25
  id_profile ServiceDate PrimaryServiceCategory     served  count  herrserv  
\
0        439  2017-12-05                     25     439 25      1         1   
1     444654  2017-01-25                     25  444654 25      2         2   
2      56454  2017-12-05                     33   56454 33      1         1   
3      56454  2017-01-25                     25   56454 25      2         2   
4     444654  2017-03-01                     25  444654 25      2         2   
5      56454  2017-01-01                     25   56454 25      2         2   
6      12222  2017-01-05                     11   12222 11      1         1   
7      12222  2017-01-30                     25   12222 25      3         3   
8      12222  2017-03-01                     25   12222 25      3         3   
9      12222  2017-03-20                     25   12222 25      3         3   

   refserv  eisserv  
0        1        1  
1        2        2  
2        1        1  
3        2        2  
4        2        2  
5        2        2  
6        1        1  
7        3        3  
8        3        3  
9        3        3  

為什么要切換字符串值? 這甚至是執行我希望執行的功能的正確方法嗎?

將整數映射到類別后,可以使用pandas.get_dummies ,然后將其與數據pandas.get_dummies合並。

您可以添加一個“計數”列,該列總計3個類別計數后綴。

df = pd.DataFrame({'id_profile': [439, 444654, 56454, 56454, 444654, 56454, 12222, 12222, 12222, 12222],
                   'ServiceDate': ['2017-12-05', '2017-01-25', '2017-12-05', '2017-01-25', '2017-03-01', '2017-01-01', '2017-01-05', '2017-01-30', '2017-03-01', '2017-03-20'],
                   'PrimaryServiceCategory': [25, 25, 33, 25, 25, 25, 11, 25, 25, 25]})

d = {11: 'eis', 33: 'ref', 25: 'her'}
df['Service'] = df['PrimaryServiceCategory'].map(d)

df = df.set_index('id_profile')\
       .join(pd.get_dummies(df.drop('PrimaryServiceCategory', 1), columns=['Service'])\
               .groupby(['id_profile']).sum())

#            ServiceDate  PrimaryServiceCategory Service  Service_eis  \
# id_profile                                                            
# 439         2017-12-05                      25     her            0   
# 12222       2017-01-05                      11     eis            1   
# 12222       2017-01-30                      25     her            1   
# 12222       2017-03-01                      25     her            1   
# 12222       2017-03-20                      25     her            1   
# 56454       2017-12-05                      33     ref            0   
# 56454       2017-01-25                      25     her            0   
# 56454       2017-01-01                      25     her            0   
# 444654      2017-01-25                      25     her            0   
# 444654      2017-03-01                      25     her            0   

#             Service_her  Service_ref  
# id_profile                            
# 439                   1            0  
# 12222                 3            0  
# 12222                 3            0  
# 12222                 3            0  
# 12222                 3            0  
# 56454                 2            1  
# 56454                 2            1  
# 56454                 2            1  
# 444654                2            0  
# 444654                2            0  

我僅對您現有的代碼進行了更改。

    import pandas as pd
    df = pd.read_csv('fakeRWclient.csv')

    df['PrimaryServiceCategory'] = df['PrimaryServiceCategory'].map({'Referral for Health Care/Supportive Services': '33', 'Health Education/Risk reduction': '25', 'Early Intervention Services (Parts A and B)': '11'})

    df['ServiceDate'] = pd.to_datetime(df['ServiceDate'], format="%m/%d/%Y")
    df['id_profile'] = df['id_profile'].apply(str)

    print(df.groupby('id_profile').PrimaryServiceCategory.count())

上面的代碼將給出如下輸出:

id_profile
439       1
12222     4
56454     3
444654    2

eisrefher的值切換為“ 25”,因為您正在遍歷變量PrimaryServiceCategory ,並且該系列中的最后一個值為“ 25”。 您將eisrefher用作迭代器變量的名稱,因此它們在每個循環中都會更改。 我認為這是一種低效的方法。 如果使用groupby並進行轉換,則更好:

df['count'] = df.groupby(['id_profile','PrimaryServiceCategory']).transform('count')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM