在DataFrame中选择特定的行和列

时间:2019-01-15 08:40:15

标签: python python-3.x pandas dataframe

我的要求有点复杂

give下面是一个DataFrame df:

                       Month1 Month2   Month3   Month4 Month5  Month6
Credit               4644.5  11142  6198.33  2830.48   5886  8381.5
No. of transactions       8      4        6       14      6       4

所以我想要的是,我想将所有这些值保存在单独的变量中。

例如,最终结果应为:

CreditMonth1 = 4644.5
CreditMonth2 = 11142 
...
so on.. and
No. of transactionsMonth1 = 8
No. of transactionsMonth2 = 4
...
so on..

使用以下代码可以实现以上结果:

CreditMonth1= df.at['Credit', 'Month1']

但是我在这里面临的挑战是列并不总是恒定的。有时它会在一段时间内全部六个月都具有价值。

例如:

                       Month1   Month2   Month3 
Credit                 5566.45  14275    6194.88  
No. of transactions       4      5        3   

预期结果

我想获取所有月份(直到6个月)的个人数据。如果在上面的3个月数据示例中,我想填写其余月份的值(即Month 4Month 6'0'

有人可以帮我吗?

3 个答案:

答案 0 :(得分:1)

使用convert [settings] [operators] INPUT [settings] [operators] OUTPUT 。看看这是否适合您

df

to_dict

输出

                   Month1  Month2   Month3   Month4  Month5  Month6
Name                                                               
Credit             4644.5   11142  6198.33  2830.48    5886  8381.5
No.oftransactions     8.0       4     6.00    14.00       6     4.0


['No.Of Transaction{} : {}'.format(key,value) for key, value in df.to_dict(orient='index')['No.oftransactions'].items()]

['{} : {}'.format(key,value) for key, value in df.to_dict(orient='index')['Credit'].items()]

更新

df

['No.Of TransactionMonth1 : 8.0',
 'No.Of TransactionMonth2 : 4.0',
 'No.Of TransactionMonth3 : 6.0',
 'No.Of TransactionMonth4 : 14.0',
 'No.Of TransactionMonth5 : 6.0',
 'No.Of TransactionMonth6 : 4.0']

['Month1 : 4644.5',
 'Month2 : 11142.0',
 'Month3 : 6198.33',
 'Month4 : 2830.48',
 'Month5 : 5886.0',
 'Month6 : 8381.5']

输出

                   Month2   Month3   Month4  Month5  Month6
Name                                                       
Credit              11142  6198.33  2830.48    5886  8381.5
No.oftransactions       4     6.00    14.00       6     4.0

credit = df.to_dict(orient='index')['Credit']
transaction = df.to_dict(orient='index')['No.oftransactions']

['{} : {}'.format('Month{}'.format(key),credit.get('Month{}'.format(key))) for key in range(1,6) ]

输出

Out[455]:

    ['Month1 : None',
     'Month2 : 11142.0',
     'Month3 : 6198.33',
     'Month4 : 2830.48',
     'Month5 : 5886.0']


['No.Of Transaction{} : {}'.format('Month{}'.format(key),transaction.get('Month{}'.format(key))) for key in range(1,6)]

答案 1 :(得分:0)

您可以使用df.iloc[some_index]之类的iloc函数来选择特定的行。之后,您可以手动遍历行。另一种选择是在循环中使用df.iterrows()。再次以这种方式,将获得每一行,如果执行for index, row in df.iterrows(),则所有数据都将位于row变量中。

更新

for index, data in df.iterrows():
  for m in ['Month_1', .. , 'Month_6']:
    if data[m] == '':
      data[m].replace('', 0, inplace=True)

答案 2 :(得分:0)

这实际上可以解决我的问题

try:
    if df.at['Credit', 'Month4']:
    SalaryMonth4 = df.at['Salary', 'Month4']
except:
    SalaryMonth4 = 0