如何推断和转换 pandas 数据框中的数据类型?

How to infer and convert dtypes in pandas dataframe?

这是我的示例数据框。我想将 AB 列中的 dtypes 转换为 booleanC 中的 stringinteger 中的 DE。 我正在尝试使用 panda 的方法 convert_dtypes() 但它对每个人都是 returns string。如何“自动”转换类型?

{'A': {0: nan,
      1: nan,
      2: nan,
      3: nan,
      4: nan,
      5: nan,
      6: nan,
      7: 'true',
      8: nan,
      9: 'true'},
     'B': {0: nan,
      1: nan,
      2: nan,
      3: nan,
      4: nan,
      5: nan,
      6: nan,
      7: 'true',
      8: nan,
      9: 'true'},
     'C': {0: 'CustomersData',
      1: 'CustomersData',
      2: 'CustomersData',
      3: 'CustomersData',
      4: 'CustomersData',
      5: 'CustomersData',
      6: 'CustomersData',
      7: 'TestData',
      8: 'CustomersData',
      9: 'CustomersData'},
     'D': {0: '4014',
      1: '4014',
      2: '4014',
      3: '4014',
      4: '4014',
      5: '4014',
      6: '4014',
      7: '500',
      8: '4014',
      9: '500'},
     'E': {0: '8',
      1: '8',
      2: '8',
      3: '8',
      4: '8',
      5: '8',
      6: '13',
      7: '13',
      8: '8',
      9: '13'}}

df.convert_types().dtypes 给出:

A string
B string
C string
D string
E string

首先检查数据框每列包含哪些数据类型。

print(df.dtypes)

然后更改所有列值类型。

df['A'] = df['A'].astype(bool)
df['B'] = df['B'].astype(bool)
df['C'] = df['C'].astype(str)
df['D'] = df['D'].astype(int)
df['E'] = df['E'].astype(int)

然后检查值是否正确转换。

print(df.dtypes)

这应该有效。如果没有,请告诉我。

Reference

对我有用的唯一方法是将其另存为 csv 并再次加载的“解决方法”。 Pandas read_csv 推断列的类型并为我工作。 很高兴知道我是否可以在没有这种解决方法的情况下解决它。